【问题标题】:Loopback : Rename file from before remote method using contextLoopback:使用上下文从远程方法之前重命名文件
【发布时间】:2018-09-01 02:52:01
【问题描述】:

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

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

谁能告诉我如何从中访问文件?

【问题讨论】:

    标签: node.js loopbackjs loopback angular-loopback


    【解决方案1】:

    我不知道之前是否可以这样做,因为我们还没有解包多部分表单。

    afterRemote 钩子包含足够的信息来重命名文件,如果你真的需要的话。这是一个基于环回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);
        }
      });
    };
    

    【讨论】:

    • 我想在上传之前而不是之后重命名。
    【解决方案2】:

    这是一个启动脚本,它将使用 UUID 重命名文件(您需要安装 UUID 包)。您可以应用时间戳等其他逻辑来重命名文件。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 2016-07-13
      相关资源
      最近更新 更多