How to validate size of file uploads in Express with Multer?

coffeescript, express, file-upload, javascript, node.js

Solution

To validate size of file uploads, you just have to use `req.file.buffer`

Below code is just a sample.

// Set your file size limit

const maxSize = 1 * 1024 * 1024; // for 1MB 

// validate file size

if (req.file.buffer.byteLength >= maxSize) {

// write code here

} else {

// write code here 

}

Problem

I'm using Multer as `multipart/form-data` middleware in Express. I'm wondering how to validate the size of uploaded files, preferably while they're being uploaded. I'm aware that you can set `limits` in the options object when instantiating Multer like so: ``` app.use multer limits: fileSize: 1024 * 1024 ``` However, this only truncates the uploaded files and doesn't allow to display an error message like "File is too big." when the file size exceeds the limit. I also checked out the event handler `onFileUploadData(file, data)` in which you have access to the `file` object and the `data` buffer. Here I can check for the current file size by checking `data.length`. It's unclear to me, though, how to handle the case in which `data.length` is bigger than the maximal upload file size that I want to allow. Ultimately, my idea is that when a request is parsed by Multer and the uploaded file is too big, I'd like to display a flash message to the user and redirect to the form, so she could try a smaller file. The `create` action of my controller looks something like this: ``` exports.create = (req, res) -> Record.create(req.body) .success (record) -> image = req.files.image uploadImage(image, record.id).then -> req.flash 'success', 'Record created.' res.redirect "/records/#{record.id}" .error (err) -> req.flash 'error', err res.redirect 'records/new' ``` The problem is that `req.files.image` is already the parsed image which is uploaded to the systems tmp folder at this point. So even checking the file size here wouldn't really allow me to protect against unwanted large file uploads. What's the best way to handle file upload validation in Express using Multer or other form-parsing middleware in general?

Original source