且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试上传到AWS S3存储桶时收到400错误请求

更新时间:2022-11-07 08:34:13

我遇到了同样的问题,经过几个小时的搜索,我能够通过将存储桶的区域添加到我请求的服务器端后端来解决此问题使用 s3.getSignedUrl()签名的URL.

I faced the same issue and after searching for hours, I was able to solve it by adding the region of my bucket to the server side backend where I was requesting a signed URL using s3.getSignedUrl().

const s3 = new AWS.S3({
    accessKeyId:"your accessKeyId",
    secretAccessKey:"your secret access key",
    region:"ap-south-1" // could be different in your case
})
const key = `${req.user.id}/${uuid()}.jpeg`

s3.getSignedUrl('putObject',{
        Bucket:'your bucket name',
        ContentType:'image/jpeg',
        Key:key
    }, (e,url)=>{
        res.send({key,url})
})

获取签名的URL后,我在客户端使用 axios.put()将图像通过URL上传到我的s3存储桶中.

After getting the signed URL, I used axios.put() at the client side to upload the image to my s3 bucket using the URL.

  const uploadConf = await axios.get('/api/uploadFile');
  await axios.put(uploadConf.data.url,file, {
    headers:{
      'Content-Type': file.type
    }
  });

希望这可以解决您的问题.

Hope this solves your issue.