Amazon S3 browser direct upload unique file name

2.9k views Asked by At

I'm using Node.js and the Amazon aws sdk for signing an upload request so I can do direct uploads from an Angular application. It works really well except I can't get unique file names. I have tried with creating unique buckets instead but then I can't get the CORS settings to work. Since it's not possible to rename the file in the browser, this is all a mystery to me. Does anyone have experience with this?

1

There are 1 answers

0
rhymn On BEST ANSWER

The resulting LoopBack.io remote method now looks like below, setting 'Key' in the parameters did the trick.

Project.signS3 = function(filename, cb){
    var aws = require('aws-sdk');

    var AWS_ACCESS_KEY = process.env.AWS_ACCESS_KEY;
    var AWS_SECRET_KEY = process.env.AWS_SECRET_KEY;
    var S3_BUCKET = '...';

    aws.config.update({
        accessKeyId: AWS_ACCESS_KEY, 
        secretAccessKey: AWS_SECRET_KEY, 
        region: 'eu-central-1',
        signatureVersion: 'v4'
    });

    // Figure out a unique filename
    var ext = filename.split('.').pop();
    var random = Math.floor(Math.random() * 900000000000000000);

    filename = random + '.' + ext;

    var s3 = new aws.S3();
    var s3_params = {
        Bucket: S3_BUCKET,
        Key: filename,
        Expires: 60,
        ACL: 'public-read'
    };

    s3.getSignedUrl('putObject', s3_params, function(err, data){

        if(err){
            console.log(err);
        }
        else{
            var return_data = {
                signed_request: data,
                url: 'https://'+S3_BUCKET+'.s3.amazonaws.com/'+filename
            };

            cb(null, return_data);
        }
    });
}