You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何使用@aws-sdk/client-s3上传文件至AWS S3?求配置示例

在React中使用@aws-sdk/client-s3实现AWS S3文件上传

步骤1:安装依赖

先安装官方SDK及大文件上传工具:

npm install @aws-sdk/client-s3 @aws-sdk/lib-storage

步骤2:编写S3上传工具函数

替换你原来的uploadFileToS3函数,以下是两种适配不同场景的上传方案:

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";

// 初始化S3客户端
const s3Client = new S3Client({
  region: "DEF", // 替换为你的S3区域,比如us-east-1
  credentials: {
    accessKeyId: "GHI", // 替换为你的Access Key ID
    secretAccessKey: "JKL" // 替换为你的Secret Access Key
  }
});

// 小文件上传(适合10MB以内的文件)
export const uploadFileToS3 = async (file, bucketName, key) => {
  try {
    const command = new PutObjectCommand({
      Bucket: bucketName,
      Key: key, // S3中存储的文件名,建议加前缀避免重复,比如`profile/${Date.now()}-${file.name}`
      Body: file,
      ContentType: file.type // 保留文件原MIME类型
    });

    const response = await s3Client.send(command);
    // 生成文件访问URL(需确保桶配置了公开可读,或通过其他权限方式访问)
    const fileUrl = `https://${bucketName}.s3.${s3Client.config.region}.amazonaws.com/${key}`;
    return { ...response, fileUrl };
  } catch (error) {
    console.error("上传失败:", error);
    throw error;
  }
};

// 大文件分块上传(自带断点续传,适合大文件)
export const uploadLargeFileToS3 = async (file, bucketName, key) => {
  try {
    const upload = new Upload({
      client: s3Client,
      params: {
        Bucket: bucketName,
        Key: key,
        Body: file,
        ContentType: file.type
      }
    });

    // 可选:监听上传进度
    upload.on("httpUploadProgress", (progress) => {
      console.log(`上传进度: ${Math.round((progress.loaded / progress.total) * 100)}%`);
    });

    const response = await upload.done();
    const fileUrl = `https://${bucketName}.s3.${s3Client.config.region}.amazonaws.com/${key}`;
    return { ...response, fileUrl };
  } catch (error) {
    console.error("大文件上传失败:", error);
    throw error;
  }
};

步骤3:修改你的updateProfile函数

调整为使用新的上传工具:

const updateProfile = async (photo) => {
  if (!photo) return;
  
  const bucketName = "ABC"; // 替换为你的S3桶名
  // 生成唯一文件名,避免覆盖
  const fileKey = `profile-photos/${Date.now()}-${photo.name}`;

  try {
    // 根据文件大小自动选择上传方式(示例:大于10MB用分块上传)
    const uploadResult = photo.size > 10 * 1024 * 1024 
      ? await uploadLargeFileToS3(photo, bucketName, fileKey)
      : await uploadFileToS3(photo, bucketName, fileKey);
    
    console.log("上传成功:", uploadResult);
    console.log("文件访问地址:", uploadResult.fileUrl);
    // 这里可以将fileUrl保存到后端或组件状态中
    return uploadResult;
  } catch (error) {
    console.error("更新头像失败:", error);
  }
};

重要安全提示

前端直接硬编码Access Key和Secret Key存在严重安全风险,攻击者可以通过浏览器开发者工具获取密钥并滥用你的AWS资源。推荐的安全方案:

  • 后端生成预签名URL,前端使用该URL直接上传文件到S3
  • 使用AWS Cognito身份池为前端提供临时访问凭证,而非长期密钥

内容的提问来源于stack exchange,提问作者Vishal Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 10:35:20