Monday 5 June 2017

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

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



via joe

No comments:

Post a Comment