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?
Asked
Active
Viewed 2,836 times
1
-
What are you doing to "get unique file names" and what problem are you experiencing? – John Rotenstein Jun 15 '15 at 05:45
-
The problem is that I simply don't know how to get unique names for my files. Since no backend is receiving the file before it is put to amazon, the file cannot be modified so I', guessing amazon would have an option for this? Thanks – rhymn Jun 15 '15 at 08:20
-
Let my rephrase the question: Is there a way to get unique file names each time a file is uploaded to Amazon aws s3 using browser direct upload? – rhymn Jun 15 '15 at 09:34
-
Could we see your code sample? If you are uploading via an HTML form, you can set a hidden "Key" field and set a filename. See https://aws.amazon.com/articles/Java/1434 – John Rotenstein Jun 15 '15 at 10:49
-
ok, I'm not using forms like that but a signed request. Although your response pointed me in the right direction :) In the parameters passed in to getSignedUrl() there is a 'Key'-key, I've now set this to a random value and everything works excellent! – rhymn Jun 15 '15 at 12:58
1 Answers
1
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);
}
});
}

rhymn
- 121
- 2
- 6