spirytus
spirytus

Reputation: 10946

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.

Upvotes: 5

Views: 9053

Answers (5)

sumedh morey
sumedh morey

Reputation: 11

There is one work around which I have used in my current project

File: make-middleware.js change "function done(err)" at end of this function

Replace Line 52: onFinished(req, function () { next(err) })

With: Line 52: onFinished(req, function () { if(err.code == 'LIMIT_FILE_SIZE') { req.fileSizeError = 1; next() } else next(err) })

And in app file you can change the code to

app.post('/upload', upload.single('upload'), function (req, res, next) {
    if(typeof req.fileSizeError != "undefined") {
        res.send({"error":"File too large"});// to display filesize error
    } else {
        res.send({"file":req.file}); // when file uploaded successfully
    }
}); 

Upvotes: 1

Ning Liu
Ning Liu

Reputation: 81

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:

Upvotes: 1

Gigo
Gigo

Reputation: 3264

The multer file object actually contains a property indicating whether the file exceeded the size limit. See https://www.npmjs.com/package/multer#multer-file-object

To accept only one file with a maximum size of 2 MB and the name "data" I did something like this:

app.use(multer({
    dest: "./uploads/",
    putSingleFilesInArray: true, // see https://www.npmjs.com/package/multer#putsinglefilesinarray
    limits: {
        files: 1,
        fileSize: 2097152 // 2 MB
    }
}));
app.post("/foo", function(request, response) {
    if (!request.files.hasOwnProperty("data")) {
        // 400 Bad Request
        return response.status(400).end();
    }
    var file = request.files.data[0];
    if (file.truncated) {
        // 413 Request Entity Too Large
        console.log("Request aborted.");
        return response.status(413).end();
    }
    // do stuff with file
});

Upvotes: 0

siavolt
siavolt

Reputation: 7077

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);
        }
    }
});

Upvotes: 4

Tom Hallam
Tom Hallam

Reputation: 1950

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!

Upvotes: 1

Related Questions