0

I have busboy in my ExpressJS app for file streaming. Now at some point I wish to send back a regular response that the file size is too large. How can I do that?

Here is my code to illustrate what I want:

     busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
          
     console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
          
           let fileSize = 0;

           file.on('data', function(data) {
           fileSize += data.length;
            console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
           });

           file.on('end', function() {
           console.log('File [' + fieldname + '] Finished');
           if (fileSize > MAXIMUM_ALLOWED_FILE_UPLOAD_SIZE) {
            //I wish to send back a regular response that the file size is too large here.
            }
           fileSize = 0;

          });
        });

        busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
          console.log('Field [' + fieldname + ']: value: ' + inspect(val));
        });

How can I achieve that?

ololo
  • 1,326
  • 2
  • 14
  • 47

1 Answers1

0

Busboy has a maximum file byte size that you can specify in the limits option which will prevent it from pushing any more data into the file than your specified limit. If you want to limit your file upload size, I'd go with that. It emits a 'limit' event on the file if it reaches the maximum size.

Busboy also handles multiple uploads-- not sure if you wanted to handle that or not. But here's a sample with a limit and multiple uploads:

var express = require('express');
var Busboy = require('busboy');
var html_escaper = require('html-escaper');
var fs = require('fs');

var escaper = html_escaper.escape;

const MAX_UPLOAD_SIZE = 10000;

var app = express();

app.get('/', function(req, res) {
    res.writeHead(200, {'Content-type': 'text/html'})
    res.write('<!doctype html><html><body>');
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">')
    res.write('<input type="file" name="upload_1">')
    res.write('<input type="file" name="upload_2">');
    res.write('<input type="submit"></form>');
    res.write('</body></html>')
    return res.end();
})

app.post('/fileupload', function (req, res) {
    var busboy = new Busboy({ headers: req.headers, limits: { fileSize: MAX_UPLOAD_SIZE } });
    var fileList = [];
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype ) {
        fileInfo = {
            'fObj': file,
            'file': filename,
            'status': 'uploaded'
        }
        fileList.push(fileInfo);
        file.on('limit', function() {
            fileInfo.status = `Size over max limit (${MAX_UPLOAD_SIZE} bytes)`;
        });
        file.on('end', function() {
            if (fileInfo.fObj.truncated) {
                if (fileInfo.status === 'uploaded') {
                    // this shouldn't happen
                    console.error(`we didn't get the limit event for ${fObj.file}???`);
                    fileInfo.status = `Size over max limit (${MAX_UPLOAD_SIZE} bytes)`;
                }
            }
        });
        file.pipe(fs.createWriteStream(`./uploads/${fileList.length}.bin`));
    });
    busboy.on('finish', function() {
        var out = "";
        fileList.forEach(o => {
            out += `<li>${escape(o['file'])} : ${o['status']}</li>`
        });
        res.writeHead(200, {'Connection': 'close'});
        res.end(`<html><body><ul>${out}</ul></body></html>`);
    })
    return req.pipe(busboy);
});

app.listen(8080);
clockwatcher
  • 3,193
  • 13
  • 13