【问题标题】:How do you handle optional file uploads with Sails JS?您如何使用 Sails JS 处理可选文件上传?
【发布时间】:2016-09-30 23:59:51
【问题描述】:

我有一个用户可以提交或不提交文件的表单。

形式:

<form method="post" action="/file/upload" enctype="multipart/form-data">
    <input type="file" name="media" />
    <input type="submit" value="Submit" />
</form>

控制器

module.exports = {
  upload: function (req, res) {
    // Check if any files were uploaded
    if (!req.file('media')._files[0]) {
        return res.send('no file given!');
    }

    req.file('media').upload({
      dirname: '/tmp/uploads'
    },function whenDone(err, uploadedFiles) {
      if (err) {
        sails.log.error('Error uploading file', err);
      }
      res.send('thanks for your file');
    });
  }
};

如果他们不上传文件,我会收到以下错误。除非我进入船长代码并注释掉抛出的错误,否则似乎没有办法捕捉或抑制它。 如何在不附加文件的情​​况下提交表单并且不让应用崩溃?

Error: EMAXBUFFER: An Upstream (`NOOP_media`) timed out before it was plugged into a receiver. It was still unused after waiting 4500ms. You can configure this timeout by changing the `maxTimeToBuffer` option.

我浏览了许多论坛和博客文章,但到目前为止没有任何帮助。

【问题讨论】:

    标签: javascript node.js forms file-upload sails.js


    【解决方案1】:

    您必须在.upload() 内进行检查。删除if 语句。

    req.file('media').upload({
      dirname: '/tmp/uploads'
    }, function whenDone(err, uploadedFiles) {
      if(uploadedFiles.length === 0){ // Check the number of files uploaded.
        return res.send('no file given!');
      }
      if (err) {
        sails.log.error('Error uploading file', err);
      }
      return res.send('thanks for your file');
    });
    

    【讨论】:

      【解决方案2】:

      当一个文件输入为空时,它看起来就像一个普通的文本输入,它会是空的,所以你可以尝试检查这样的东西:

       if(typeof req.param('media') !== 'undefined' && req.param('media').length == 0)) {
              return res.send('no file given!');
         }else {  //handle the file upload }
      

      【讨论】:

        【解决方案3】:

        您可以使用noMoreFiles() 中止流。

        const skipperUpstream = req.file('media');
        
        // skipperUpstream._files is an internal array containing the uploaded files for key `media`
        // here i just expecting a single file, or none
        const file = skipperUpstream._files[0];
        
        if (!file) {
          // `skipperUpstream.__proto__` is `Upstream`. It provides `noMoreFiles()` to stop receiving files.
          // It also clears all timeouts: https://npmdoc.github.io/node-npmdoc-skipper/build/apidoc.html#apidoc.element.skipper.Upstream.prototype.noMoreFiles
          skipperUpstream.noMoreFiles();
          return;
        }
        
        skipperUpstream.upload(/* your stuff */);
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-26
          • 2017-01-04
          • 2015-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多