Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop upload and redirect in busboy if mime type is invalid?

Tags:

node.js

busboy

I am fairly new to Node.js, and I am using Express and Busboy-Connect to create a simple file upload form, for wav files only. Here is what I am trying to do : - start the upload - if the mimetype is not wav, redirect to an error page - else : write the file on the server and redirect back.

If the mimetype is valid, everything works fine, but if it isn't I cannot redirect and the browser is just hanging and eventually times out. My understanding of it is that the browser doesn't want to redirect because it is waiting for the upload to finish, but how can I cancel the upload then within my js code ? I could work around the issue and write the file then delete it if it's not the right mimetype, but I think it's a bit stupid to do that, I'd rather find a way to trigger an event that will stop it and redirect immediately. Here is (a snippet of) my app code :

app.get('/', function (req, res) {
    res.render(__dirname + '/public/index.ejs', {error: 0});
});

app.get('/error', function (req, res) {
    res.render(__dirname + '/public/index.ejs', {error: 1});
});

app.post('/upload', function (req, res) {
    var timestamp = new Date().getTime().toString();
    //console.log(timestamp);
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {

        if ("audio/wav" != mimetype)
        {
           console.log("invalid mimetype"); // that prints ok
           // req.busboy.end();  // I tried that but it doesn't work
           res.redirect('/error');


        }
        else
        {
            console.log("Uploading: " + mimetype); 
            fstream = fs.createWriteStream(__dirname + '/tmp/' + timestamp + filename);
            file.pipe(fstream);
            fstream.on('close', function () {
                res.redirect('back');

            });
        }
    });



});

Can anyone point me in the right direction? Thank you for your help !

like image 788
zoubida13 Avatar asked May 01 '15 11:05

zoubida13


People also ask

Can MIME type be faked?

Checking for mime type in php is pretty easy but as far as I know mime can be spoofed. The attacker can upload a php script with for example jpeg mime type. One thing that comes to mind is to check the file extension of the uploaded file and make sure it matches the mime type.


1 Answers

Alright I found it in the docs of npm, if you think anyone could be interested in finding this answer from a google search you can leave it resolved, otherwise feel free to close/remove this post.

Basically there is a function on the filestream that need to be called to unblock busboy, so all I had to do to make it work is to add

file.resume();

before redirecting to the error page.

like image 96
zoubida13 Avatar answered Oct 10 '22 22:10

zoubida13