Search code examples
node.jsexpressbusboy

connect-busboy catch no file scenario


I am using connect-busboy to upload a file for attachment of email. The code is working fine if one file is present. However, I want to catch the scenario where there is no file attached/uploaded.

Initially i thought I will check for the size of file to be zero, but then I realized that busboy.on('file') itself is not getting triggered.

How can I check if no file is uploaded and continue to the next step ?

Below is the code:

if (req.busboy) {
    req.busboy.on('field', function (fieldname, value) {
        console.log('Field [' + fieldname + ']: value: ' + value);
        // collecting email sending details here in field
    });

    var now = (new Date).getTime();
    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        var attachmentfile = '/tmp/' + now + '.' + filename;
        fstream = fs.createWriteStream(attachmentfile);
        file.pipe(fstream);
        fstream.on('close', function () {
            console.log("Upload Finished of " + filename);
            console.log('Time to upload: ' + utility.getFormattedTime((new Date).getTime() - now));
            attachment.file = { 'name': filename, 'location': attachmentfile };

            // send email code

            return res.send('email sent successfully');
        });
    });

    req.busboy.on('finish', function () {
        // validating if input from reading field values are correct or not
    });
} else {
    res.error('No file attached');
}

The curl command which I am using for testing with no file is:

curl -X POST \
    http://localhost:3000/email/ \
    -H 'Cache-Control: no-cache' \
    -H 'content-type: multipart/form-data;' \
    -F 'data={'some json object' : 'json value'}'

if I add -F 'file=@location' in the above curl command, code works fine.

What am I missing ?


Solution

  • You can use a variable which you set to true if there was a file.

    if (req.busboy) {
    
        var fileUploaded = false;
    
        req.busboy.on('field', function (fieldname, value) {
            ...
        });
    
        var now = (new Date).getTime();
        req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
    
            fileUploaded = true;
            ...
        });
    
        req.busboy.on('finish', function () {
    
            if (!fileUploaded) {
    
                res.error('No file attached');
    
            } else {
    
                // ----- a file has been uploaded
            }
    
        });
    } else {
        res.error('No file attached');
    }