首页 > 解决方案 > React + Node - 无法将图像上传到 S3

问题描述

我正在尝试使用 AWS SDK 从 React 上传图像。

我正在遵循的过程:

从后端获取签名 URL(返回 200)

使用返回的签名 url 使用 PUT 请求(返回 400 错误)

// returns the file name which will be uploaded and the signed url
    const uploadConfig = await axios.get('/api/upload/image/sign');
// upload the actual file
    await axios.put(uploadConfig.data.url, image, {
      headers: {
        'Content-Type': image.type
      }
    });

错误

Request URL: https://<bucket_name>.s3.amazonaws.com/5f8879747732900023eef381/e87a4a2f-b58b-478c-9d1b-fe769233ed20.jpeg?AWSAccessKeyId=<access_key>&Content-Type=image%2Fjpeg&Expires=1602781066&Signature=Kj15gko%2BYoqz212#4GuOFDc12D8$%^
Request Method: PUT
Status Code: 400 Bad Request
Remote Address: 53.213.67.151:443
Referrer Policy: strict-origin-when-cross-origin

S3 存储桶 cors 配置:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <ExposeHeader>ETag</ExposeHeader>
    <ExposeHeader>x-amz-meta-custom-header</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

S3 政策

{
    "Version": "2012-10-17",
    "Id": "Policy1602682508288",
    "Statement": [
        {
            "Sid": "Stmt1602682506434",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::<bucket_name>/*"
        }
    ]
}

标签: node.jsreactjsamazon-web-servicesamazon-s3

解决方案


我认为有关 S3 政策的问题。尝试将 PutObject 或 (*) 策略附加到您的 S3 存储桶。如果不起作用,请检查您的符号生成端点和结果。

更多信息你可以在这里找到


推荐阅读