Rename file before upload using remote hooks in lo

2019-06-09 18:57发布

问题:

I am having difficulty in renaming a file before upload in loopback component storage. As it seems, loopback does'nt provide a built-in option for the same. For uploading from a angular form, I have used the angular uploader beforeupload method to change the filename using following method:

this.fileExtension = '.' + item.file.name.split('.').pop();
item.file.name = Math.random().toString(36).substring(7) + new Date().getTime() + this.fileExtension;

Is it possible to perform the same operations in before remote hook of the upload method in loopback component storage? My intention is to do the same file name change operation for api requests coming from mobile devices. If a remote hook cannot do the same, is there any other method for achieving the same result? Thanks in advance!

回答1:

Say you have storage DS defined in datasources.json.

You can do it in a boot script :

//server/boot/any.js
module.exports = function(app){
app.dataSources.storage.connector.getFilename = function (file, req, res) {
  //file.name is original filename uploaded
  var filename = req.query.filename || 'general.ext';
  return filename;
}
};

and add filename in the upload url.

e.g : /containers/my-container/upload?filename=profile.jpg