我有一个用户可以提交或不提交文件的表单。
表格:
<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.
我已经通过了许多论坛和博客文章,但到目前为止没有任何帮助。
答案 0 :(得分:0)
您必须在.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');
});
答案 1 :(得分:0)
当文件输入为空时,它看起来像普通的文本输入,它将是空的,所以你可以尝试检查这样的事情:
if(typeof req.param('media') !== 'undefined' && req.param('media').length == 0)) {
return res.send('no file given!');
}else { //handle the file upload }
答案 2 :(得分:0)
您可以使用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 */);