getting 400 Bad Request when trying to upload to aws s3 bucket

僤鯓⒐⒋嵵緔 提交于 2020-12-10 04:31:22

问题


I sign the URL on my server and send it back to the client which works fine. This is how that function looks

const aws = require('aws-sdk'),
    config = require('config'),
    crypto = require('crypto');


module.exports = async function(file_type) {

    aws.config.update({accessKeyId: config.AWS_ACCESS_KEY, secretAccessKey: config.AWS_SECRET_KEY})

    const s3 = new aws.S3();

    try {
        if (!file_type === "image/png") {
            return ({success: false, error: 'Please provide a valid video format'});
        }
        let buffer = await crypto.randomBytes(12);

        let key = buffer.toString('hex');

        let options = {
            Bucket: config.AWS_S3_BUCKET,
            Key: key,
            Expires: 60,
            ContentType: file_type,
            ACL: 'public-read',
        }

        let data = await s3.getSignedUrl('putObject', options);
        console.log('data was', data)
        return ({
            success: true,
            signed_request: data,
            url: ('https://s3.amazonaws.com/' + config.AWS_S3_BUCKET + '/' + key),
            key,
        });
    } catch (error) {
        console.log('the error was', error)
        return ({
            success: false,
            error: error.message,
        })
    }
}

So this works fine and winds up getting me a url like

https://mybucket.s3.amazonaws.com/a33b4a43f23fc41de9ddck1k?AWSAccessKeyId=ADIFJDGPMRFRGLXSYWPQ&Content-Type=image%2Fpng&Expires=1496716543&Signature=0zcx%2BFzWUoeFD02RF2CQ2o0bLmo%3D&x-amz-acl=public-read

Then when I get that url back on the client.. i send a PUT request using axios with a function like -

function uploadToS3(file, signedRequest, callback){

    var options = {
        headers: {
            'Content-Type': file.type
        }
    };

    axios.put(signedRequest, file, options)
        .then(result =>{
            console.log('the result was', result)
            callback(result)
        })
        .catch(err =>{
            callback(err)
        })

}

The only I'm getting back is (400) Bad Request


回答1:


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})
})

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.




回答2:


Guess bad header you provided

Works for me

 function upload(file, signedRequest, done) {
  const xhr = new XMLHttpRequest();
  xhr.open('PUT', signedRequest);
  xhr.setRequestHeader('x-amz-acl', 'public-read');
  xhr.onload = () => {
    if (xhr.status === 200) {
      done();
    }
  };

  xhr.send(file);
}


来源:https://stackoverflow.com/questions/44380577/getting-400-bad-request-when-trying-to-upload-to-aws-s3-bucket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!