Search code examples
amazon-s3sails.jsskipper

How to change random uploaded filename in S3 - Sails.JS


currently I'm using SailsJS to create my own web-apps. And I'm 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 already put the 'path' and 'original filename' to MongoDB. But the 'filename' inside S3 is already changed with 'random name'. So, is it possible to change to 'original filename' while uploading? OR automatically change to 'original filename' when user want to download it?

Regards, John Elmer Semaya


Solution

  • After looking skipper documentation I have found about saveAs options. Only have to put it inside req.file('name').upload to let it saved with your original name or with another custom name.

    this is the 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
    },
       ...
    });