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

1

7

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 !

Lavabo answered 1/5, 2015 at 11:22 Comment(0)
L
4

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.

Lavabo answered 1/5, 2015 at 14:0 Comment(1)
It worked for me, I posted my solution here if anybody needs it https://mcmap.net/q/835798/-node-busboy-abort-upload/…Hortensehortensia

© 2022 - 2024 — McMap. All rights reserved.