1

I want to rename file from before remote hook using context.

 container.beforeRemote('upload', function (context, res, next) {
      /////rename file
}

Can anyone tell me how can i access files from this?

Ankur Akvaliya
  • 2,989
  • 4
  • 28
  • 53

2 Answers2

0

I don't know if it's possible to do it before because we haven't unpacked the multipart form yet.

The afterRemote hooks contains enough information to rename the file if you really need to. Here's an example built on top of loopback's default storage example

app.start = function() {
  // Adding an operation hook which renames the recently uploaded file

  var container = app.dataSources.storage.models.container;

  container.afterRemote('upload', (context, res, next) => {

    // The file object is stored in the res param
    let file = res.result.files.file[0];

    // Get the filepath of our datasource, in this case `storage`.
    let root = container.dataSource.settings.root;

    // Get the full path of the file we just uploaded
    // root/containerName/filename.ext
    let filePath = path.resolve(root, file.container, file.name);

    //  aand rename
    fs.rename(filePath, path.resolve(root, file.container, 'newFile.txt'), () => console.log('renamed!'));
  });


  return app.listen(function() {
    app.emit('started');
    var baseUrl = app.get('url').replace(/\/$/, '');
    console.log('Web server listening at: %s', baseUrl);
    if (app.get('loopback-component-explorer')) {
      var explorerPath = app.get('loopback-component-explorer').mountPath;
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
    }
  });
};
0

Here is a boot script which will rename the file using a UUID (You need to install UUID package). You can apply other logic such as timestamp etc for renaming the file.

var uuid = require('uuid-v4');
module.exports = function(app) {
    var uuid = require('uuid-v4');
    module.exports = function(app) {
        app.dataSources.storage.connector.getFilename = function(origFilename, req, res) {
            var origFilename = origFilename.name;
            var parts = origFilename.split('.'),
                extension = parts[parts.length - 1];
            return uuid() + '.' + extension;
        }
    }
}