通过预先签名的 url 上传 AWS S3 返回 400 错误请求

the*_*oat 5 javascript amazon-s3 node.js reactjs

我正在尝试AWS s3通过向预签名 URL发出PUT 请求来上传文件。我已经在 s3 仪表板上配置了 CORS。

反应代码

  const submit = async () => {
    const response = await axios.get("http://localhost:8080/api/upload");
    console.log(response.data);
    const upload = await axios.put(response.data.url, file, {
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Content-Type": file.type
      }
    });
  };
Run Code Online (Sandbox Code Playgroud)

Node.js 代码

const s3 = new AWS.S3({
  accessKeyId: config.aws.accessKeyId,
  secretAccessKey: config.aws.secretAccessKey
});
app.get("/api/upload", (req, res) => {
  const key = `${uuid()}.jpeg`;
  s3.getSignedUrl(
    "putObject",
    {
      Bucket: "bucket-name",
      ContentType: "image/jpeg",
      Key: key
    },
    (err, url) => {
      res.status(200).json({ key, url });
    }
  );
});
Run Code Online (Sandbox Code Playgroud)

当我尝试向PUT预签名 URL发出请求时,出现下一个错误:

PUT https://bucket-name.s3.amazonaws.com/dd7eb480-9115-11e9-bb14-75395bf4d226?AWSAccessKeyId=AKIAZPROFMOUP5TZZOIM&Content-Type=%2A&Expires=1560786770&Signature=c2ap3CcLKj%2FUD8yHtiHTNTnWJT4%3D 400(错误请求)createError.js: 17 Uncaught (in promise) Error: Request failed with status code 400 at createError (createError.js:17) at结算 (settle.js:19) at XMLHttpRequest.handleLoad (xhr.js:60)

小智 0

创建 s3 实例的方法是将 Region 替换为您的存储桶的区域:

AWS.config.update({region: 'REGION'});

const s3 = new AWS.S3({
  apiVersion: '2006-03-01',
  accessKeyId: keys.accessKeyId,
  secretAccessKey: keys.secretAccessKey
});
Run Code Online (Sandbox Code Playgroud)