How to change arbitrary uploaded filename in S3 - Sails.JS
I am currently using SailsJS to build my own web applications. And I am using skipper-s3 to upload files to AWS S3. And this is my code:
req.file('uploadFile').upload({
adapter: require('skipper-s3'),
key: 'KEY',
secret: 'SECRET',
bucket: 'BUCKET',
ACL: 'public-read'
}, function whenDone(err, filesUploaded) {
if (err) {
console.log(err);
return res.negotiate(err);
}
var pt = {
user: req.session.User.id,
agency: req.param('id'),
path: filesUploaded[0].extra.Location,
filename: filesUploaded[0].filename
};
Transaction.create(pt, function TransactionCreated(err, trans){
if(err) return next(err);
return res.ok({
files: filesUploaded,
textParams: req.params.all(),
trans: trans
});
})
});
So, I've already put "path" and "original filename" in MongoDB. But the "filename" inside S3 has already been changed to a "random name". So, is it possible to jump to the "original filename" at boot time? OR automatically change to "original filename" when the user wants to download it?
Best regards, John Elmer Semaya
source to share
After looking through the documentation for the skipper, I found about the saveAs
options. All that remains is to put it inside req.file('name').upload
so that it will be saved with your original name or some other custom name.
This is an example:
var newFilename = req.file('uploadFile')._files[0].stream.filename;
req.file('uploadFile').upload({
adapter: require('skipper-s3'),
key: 'KEY',
secret: 'SECRET',
bucket: 'BUCKET',
ACL: 'public-read,
saveAs: newFilename //this is how you put custom name when upload file
},
...
});
source to share
You can set the key parameter s3params.
const options = {
adapter: require('skipper-s3'),
key: 'KEY',
secret: 'SECRET',
bucket: 'BUCKET',
s3params: {Key: 'full/path/to/file.jpg'} //no leading slash prevents empty folder
}
const adapter = require('skipper-better-s3')(options),
receiver = adapter.receive();
req.file('uploadFile').upload(receiver, function(err,filesUploaded){
//do something...
})
//More useful below
const fs = require('fs');
const file = fs.createReadStream('/tmp/my-file.jpg');
receiver.write(file, () => {
console.log(file.extra);
});
source to share