Search code examples
javascriptnode.jsformidable

Validate file extension before uploading whole file formidable (node.js)


I have a Node.JS server working as an router, it's possible to make post requests to it to upload files, only jpg/png/jpeg extensions should be allowed what I'm currently doing is:

var form = new formidable.IncomingForm(),
    files = [],
    postToFolder,
    source,
    size = 0,
    dest;

postToFolder = '/path/';

form.on('file', function (field, file) {
    var fileType = file.type.split('/').pop();

     if (fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg') {
        // alot of stuff
         }
        else{
            console.log('invalid filetype');
            fs.unlinkSync(file.path);
            console.log('Deleted: ' + file.path);
        }

This code works but it uploads the files to the /tmp/ folder and then has to delete them if they're invalid. It would be better for performance if I could check the file extension before the file fully has been uploaded. Would anyone know how? I've tried googling with no luck and came across some answers that aren't applicable with Formidable.

EDIT:

So I found out this triggers RIGHT before it starts, but it does start writing the file, cancelling it or breaking the server during it lead to my whole file disk being written full a few times, documentation is really bad so I cant find anything that would allow me to "skip" the file

form.on('fileBegin', function(field, file) {
    var fileType = file.type.split('/').pop();

    if (fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg') {

    }
    else{

    }
});

Solution

  • I've found the solution in a other SO post, it's the same answer but the answer was hard to find because I was looking specifically for something called before the file is uploaded. The code I am using now (you can remove filetype check in the form.on('file'

    form.onPart = function (part) {
        if(!part.filename && part.filename.match(/\.(jpg|jpeg|png)$/i)) {
            this.handlePart(part);
        }
        else {
            console.log(part.filename + ' is not allowed');
        }
    }
    

    Source uploading files using express.js and node, limiting extensions

    EDIT: I would also like to point out that this doesn't disallow an user to rename an .exe to a .jpg and then he can get it through.