节点Busboy中止上传 [英] Node Busboy abort upload

查看:174
本文介绍了节点Busboy中止上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 busboy ,将我上传的文件写入缓冲区并对其进行一些验证(宽度,高度和文件大小)。我不能为我的生活找出如何中止/停止流一旦我发现上传错误。

I'm using busboy, writing my uploaded file to a buffer and performing some validation on it (width, height and filesize). I can't for the life of me figure out how to abort / stop the stream once I find something wrong with the upload.

例如,如果我想要允许500kb的最大文件大小,我会跟踪缓冲区的大小,因为它正在上传,我想中止如果大小超过500kb。

For instance if I have a max filesize of 500kb that I want to allow, I keep track of the size of the buffer as it's uploading and I want to abort if the size is over 500kb.

这是我的代码的简化版本。

Here's a simplified version of my code.

var self = this;
var busboy = new Busboy({
    headers: self.req.headers,
    limits: {
        files: 1
    }
});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {

    file.fileRead = [];
    var size = 0;
    file.on('data', function(chunk) {

        size += chunk.length;

        /* DO VALIDATION HERE */
        if( size > 500000) {
            /*** ABORT HERE ***/
        }


        file.fileRead.push(chunk);
    });

    file.on('end', function() {
        var data = Buffer.concat(file.fileRead, size);
        // ... upload to S3
    });

    self.req.pipe(busboy);
});


推荐答案

好的,所以我有同样的问题,它与 file.resume();

Ok, so I had the same problem and I solved it with file.resume();

var fstream;
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {

    // Validate file mimetype
    if(mimetype != 'image/png'){
        file.resume();
        return res.json({
            success: false,
            message: 'Invalid file format'
        });
    }

    // Upload
    fstream = fs.createWriteStream(__dirname + '/tmp/' + timestamp + filename);
    file.pipe(fstream);
    fstream.on('close', function () {
        return res.json({
            success: true
        });
    });

});

req.pipe(req.busboy);

这篇关于节点Busboy中止上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆