Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send response to client when files is too large with Multer

I'm using NodeJs Multer to upload files. I need to send response back to a client when file user tries to upload is too large. The problem is that onFileSizeLimit only has file as argument and I dont know how to send response to client. What I need to do is basically soomething like below:

app.use('/users/gyms/upload-logo', multer({
    // other settings here then:
    onFileSizeLimit: function (file) {
        // but res (response) object is not existing here
        res.json({
            message: "Upload failed",
            status: MARankings.Enums.Status.FILE_TOO_LARGE
            // status: -6
        });
    }
});

res object dosent exists in there however and I'm wondering what is the best way to send some sort of response to client.

like image 816
spirytus Avatar asked Mar 10 '15 12:03

spirytus


3 Answers

try this:

app.use('/users/gyms/upload-logo', multer({
    // other settings here then:
    onFileSizeLimit: function (file) {
        // but res (response) object is not existing here
        file.error = {
            message: "Upload failed",
            status: MARankings.Enums.Status.FILE_TOO_LARGE
            // status: -6
        };
    }, onFileUploadComplete: function (file, req, res) {
        if (file.error){
            res.send(file.error);
        }
    }
});
like image 161
siavolt Avatar answered Oct 21 '22 17:10

siavolt


In this case, it's good to remember that Multer itself is just a (middleware) function that Express calls to get its response.

You could perhaps try with this:

app.use('/users/gyms/upload-logo', function(req, res, next) {

    var handler = multer({

        // other settings here then:
        onFileSizeLimit: function (file) {

            // res does exist here now :)
            res.json({
                message: "Upload failed",
                status: MARankings.Enums.Status.FILE_TOO_LARGE
                // status: -6
            });

        }

    });

    handler(req, res, next);

});

This basically aliases multer to handler, passes req, res, next from the Express callback, and means you get access to the req, res, next variables from within Multer's configuration.

I haven't tested this but I think the theory is sound!

like image 27
Tom Hallam Avatar answered Oct 21 '22 18:10

Tom Hallam


This is an issue which has not been resolved by the author of multer yet. This github issue has quite a lot of discussion about it:

like image 1
Ning Liu Avatar answered Oct 21 '22 18:10

Ning Liu