【问题标题】:pass file stream for model processing in Sails.js在 Sails.js 中传递文件流以进行模型处理
【发布时间】:2015-12-09 23:03:41
【问题描述】:

我有自定义 Create 方法,我想在我的 Sails.js 应用程序中为我的 Founder 模型添加。该应用程序包括文件和普通表单字段。遵循此tutorial 的建议。 我正在尝试将大量控制器代码卸载到 Founder 模型中进行处理。这让事情有点尴尬,并导致以下错误。

TypeError: Cannot read property 'stream' of undefined

这是我的模型函数中这一行的结果:

createFromForm: function(opts, cb){
  var id = opts.id;
  var params = opts.params;
  var newFilename = opts.avatartwo._files[0].stream.filename;

在第四行。现在在控制器中,类似的代码将是,遵循 Sails 语法:

var newFilename = opts.req.file('avatartwo')_files[0].stream.filename;

我只是简单地将req.file('avatartwo') 的结果写入我通过以下方式传递给模型函数的选项中:

var opts = {
    params: params,
    id: id,
    avatartwo: req.file('avatartwo')
  };

虽然这似乎有问题,但因为我不是最了解这个主题的,我不知道为什么。我很欣赏这里的一些说明。谢谢!

【问题讨论】:

    标签: javascript node.js forms sails.js crud


    【解决方案1】:

    要在sailsjs 中处理文件上传,请使用以下代码。

       var uploadedFile = req.file('some_file').upload({
        dirname: 'path to store the file',/* optional. defaults to assets/uploads I guess*/
        saveAs: 'new file name', /* optional. default file name */
        maxBytes: 5 * 1024 * 1024 //5 MB
    }, function(err, uploadedFiles) {
        if (err) {
            return res.json(500, err);
        } else if (uploadedFiles.length === 0) {
            // handle if no files were uploaded  
        } else {
            // do processing with file descriptor available at  uploadedFiles[0].fd
            //  pass to model in your case
            var opts = {
                    params: params,
                    id: id,
                    avatartwo: uploadedFiles[0].fd
            };
    
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      • 2019-09-23
      • 2023-03-19
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多