环回:使用上下文从远程方法之前重命名文件

时间:2018-03-22 15:26:50

标签: node.js loopbackjs loopback angular-loopback

我想使用上下文从远程钩子之前重命名文件。

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

任何人都可以告诉我如何从中访问文件?

2 个答案:

答案 0 :(得分:0)

我之前不知道是否可以这么做,因为我们还没有打开多部分表格。

如果您确实需要,afterRemote挂钩包含足够的信息来重命名文件。这是一个建立在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);
    }
  });
};

答案 1 :(得分: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;
        }
    }
}