提问者:小点点

如何使用node、createPresignedPost和fetch将图像文件直接从客户端上传到AWSS3


我正在服务器上使用S3.createPresignedPost()生成一个AWS S3预签名post对象。然后,我试图使用预签名的post url&字段使用fetch从客户机直接上传一个文件到S3 bucket,但得到的是403 PROBIDE

我尝试手动将表单字段添加到FormData对象中,以直接匹配以下示例:https://docs.aws.amazon.com/amazons3/latest/api/sigv4-post-example.html,但仍然收到403错误。

用于生成post对象的服务器端函数


    const AWS = require("aws-sdk/global");
    const S3 = require("aws-sdk/clients/s3");
    const uuidv4 = require("uuid/v4");

    AWS.config.update({
      accessKeyId: process.env.S3_KEY_ID,
      secretAccessKey: process.env.S3_SECRET_KEY,
      region: "us-east-1"
    });

    const s3 = new S3();

    const getPresignedPostData = (bucket, directory) => {
      const key = `${directory}/${uuidv4()}`;
      const postData = s3.createPresignedPost({
        Bucket: bucket,
        Fields: { Key: key, success_action_status: "201" },
        Conditions: [{ acl: "public-read" }],
        ContentType: "image/*",
        Expires: 300
      });
      return postData;
    };

返回以下内容:


    {
      fields: {
        Key: "5cd880a7f8b0480b11b9940c/86d5552b-b713-4023-9363-a9b36130a03f"
        Policy: {Base64-encoded policy string}
        X-Amz-Algorithm: "AWS-HMAC-SHA256"
        X-Amz-Credential: "AKIAI4ELUSI2XMHFKZOQ/20190524/us-east-1/s3/aws4_request"
        X-Amz-Date: "20190524T200217Z"
        X-Amz-Signature: "2931634e9afd76d0a50908538798b9c103e6adf067ba4e60b5b54f90cda49ce3"
        bucket: "picture-perfect-photos"
        success_action_status: "201"
      },
      url: "https://s3.amazonaws.com/picture-perfect-photos"
    }

我的客户端函数看起来像:



    const uploadToS3 = async ({ fields, url }, file) => {
        const formData = new FormData();
        Object.keys(fields).forEach(key => formData.append(key, fields[key]));
        formData.append("file", file);

        try {
          const config = {
            method: "POST",
            body: formData
          };
          const response = await fetch(url, config);

          if (!response.ok) {
            throw new Error(response.statusText);
          }

          const data = await response.json();
          return data;
        } catch (err) {
          console.log(err.message);
        }
      };

我的S3桶CORS配置如下:


    <?xml version="1.0" encoding="UTF-8"?>
    <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>DELETE</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    </CORSConfiguration>

我希望得到当success_action_status:“201”设置时发送的XML文档,但我一直在得到403禁止


共1个答案

匿名用户

我刚经历过同样的问题。

Put内容-*添加到S3控制台中的S3桶的CORS规则中。

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedHeader>Content-*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

向服务器发出post请求以获取预签名的S3 URL。post请求应在正文中包含文件名和mime类型:

快速路线:

app.post("/s3-signed-url",async (req, res, next)=>{
    const s3 = new AWS.S3();
    const url = await s3.getSignedUrlPromise('putObject', {
        Bucket: "BUCKET_NAME",
        Key: req.body.name,
        ContentType: req.body.type,
        Expires: 60,
        ACL: 'public-read',
    });
    res.json({signedUrl: url})
});

选择要上载的文件时的异步函数中的客户端代码:

async function onFileDrop(file){
    const {name, type} = file; // I use react-dropzone to obtain the file.
    const options = {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({name,type})
    }
    const rawResponse = await fetch("/s3-signed-url", options)
    const {signedUrl} = await rawResponse.json();

    // After you obtain the signedUrl, you upload the file directly as the body.
    const uploadOptions = { method: 'Put', body: file,}
    const res = await fetch(signedUrl, uploadOptions);
    if(res.ok) {
        return res.json()
    }
}

我的致命错误是,在上载带有签名URL的文件时,我在uploadoptions中添加了冗余头。我遇到其他线程,它们声称我必须显式添加“content-type”头:

`const wrongUploadOptions = { method: 'Put', body: file, headers:{"Content-Type": file.type, "x-amz-acl": public-read}}`

但这在我的情况下是完全没有必要的,这就是我得到403错误的原因。