【问题标题】:Stop request during file upload in NodeJs在 NodeJs 中的文件上传期间停止请求
【发布时间】:2014-05-08 12:40:59
【问题描述】:

我正在编写一个图片上传器,我想将图片的大小限制在 3mb 以下。在服务器端,我可以检查标题中图像的大小,如下所示(使用 express):

app.post('/upload', function(req, res) {
  if (+req.headers['content-length'] > 3001000) { // About 3mb
     // Do something to stop the result
     return res.send({'error': 'some kind of error'});
  }
  // Stream in data here...
}

我试图通过(和排列)来停止请求

req.shouldKeepAlive = false;
req.client.destroy();
res.writeHead(200, {'Connection': 'close'});
res.end()

它们都没有真正“破坏”请求以防止上传更多数据。 req.client.destroy() 似乎冻结了下载,但是 res.send({error... 没有被发回。

救命!

【问题讨论】:

  • 文件是否使用标准格式上传发送?
  • 是的,使用 enctype="multipart/form-data", accept="image/*"
  • 换个说法,可以在浏览器的客户端添加/修改请求头吗?
  • 很确定这是可能的——不过我有更新,看来真正的问题不在于节点,而在于 NginX。它在将上传发送到节点之前缓冲上传。 wiki.nginx.org/HttpCoreModule#client_body_buffer_size我必须进一步调查...
  • 我认为您想要的设置是 client_max_body_size wiki.nginx.org/NginxHttpCoreModule#client_max_body_size 它将向客户端发送 413“请求实体太大”响应。不过,我认为浏览器不太了解 413,因此如果这是面向公众的上传工具,您可能需要使用隐藏的 iframe 或类似工具来管理文件上传。

标签: file-upload node.js


【解决方案1】:

抛出一个错误并捕获它。它将停止文件上传,允许您发送响应。

try { throw new Error("Stopping file upload..."); } 
catch (e) { res.end(e.toString()); }

这有点骇人听闻,但它确实有效......

【讨论】:

  • 我不知道你的回答为什么不被接受。它在 2017 年对我有用!
【解决方案2】:

这是我的解决方案:

var maxSize = 30 * 1024 * 1024;    //30MB
app.post('/upload', function(req, res) {

    var size = req.headers['content-length'];
    if (size <= maxSize) {
        form.parse(req, function(err, fields, files) {
            console.log("File uploading");
            if (files && files.upload) {
                res.status(200).json({fields: fields, files: files});
                fs.renameSync(files.upload[0].path, uploadDir + files.upload[0].originalFilename);
            }
            else {
              res.send("Not uploading");
            }
        });
    }
    else {
        res.send(413, "File to large");
    }

如果在得到响应之前浪费了客户端的上传时间,请在客户端javascript中进行控制。

if (fileElement.files[0].size > maxSize) {
    ....
}

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多