如何在 S3 中更改随机上传的文件名 - Sails.JS

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

目前我正在使用 SailsJS 创建我自己的网络应用程序。我正在使用 skipper-s3 将文件上传到 AWS S3。这是我的代码:

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
    });
  })
});

所以我已经把 'path' 和 'original filename' 放到了 MongoDB。但是 S3 里面的 'filename' 已经改成了 'random name'。那么,上传的时候可以改成'original filename'吗?或者当用户想要下载时自动更改为 'original filename'?

此致, 约翰·埃尔默·塞马亚

在查看 skipper documentation 之后,我找到了 saveAs 个选项。只需要将它放在 req.file('name').upload 中,让它以您的原始名称或其他自定义名称保存。

这是例子:

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

可以设置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);
});