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.
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);
});
                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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With