In this tutorial, we aim to learn how to validate file formats and sizes using Multer in Express.js. Multer is a node.js middleware used for handling multipart/form-data, primarily used for uploading files. We will learn how to control which files are allowed to be uploaded and their maximum size.
By the end of this tutorial, you should be able to:
- Understand how to use Multer to upload files in Express.js.
- Validate file formats and sizes using Multer.
- Implement these techniques in your Express.js app.
Prerequisites:
- Basic understanding of JavaScript.
- Familiarity with Node.js and Express.js.
Multer is a middleware that processes multipart/form-data. It is mostly used for uploading files. Multer adds a body
object and a file
or files
object to the request object. The body
object contains the values of the text fields of the form, the file
or files
object contains the files uploaded via the form.
To validate file formats and sizes, you can customize the storage options or use the fileFilter
and limits
options.
Example 1: Basic file upload with Multer
First, let's look at a simple example of uploading a file with Multer.
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully.');
});
In this code:
upload.single('file')
middleware processes the file upload.Example 2: Validating file format
Now, let's add a fileFilter
to validate the file format.
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/')
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
const fileFilter = function(req, file, cb) {
// Only allow files with .jpg, .jpeg, .png, .gif extensions
if (file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'image/gif') {
cb(null, true);
} else {
cb(new Error('Invalid file type, only JPG, JPEG, PNG and GIF is allowed!'), false);
}
};
const upload = multer({
storage: storage,
fileFilter: fileFilter
});
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully.');
});
In this code:
fileFilter
.fileFilter
function checks the mimetype
of the uploaded file and only allows certain types.Example 3: Validating file size
Finally, let's add a limits
option to validate the file size.
const upload = multer({
storage: storage,
fileFilter: fileFilter,
limits: {
fileSize: 1024 * 1024 * 5 // we are allowing only up to 5mb files
}
});
In this code:
limits
option to the Multer configuration.fileSize
limit is set to 5MB.In this tutorial, we learned how to:
fileFilter
and limits
options.To continue learning, you can explore more about Multer's options, such as inMemoryStorage
for storing the files in memory as Buffer objects.
fileFilter
function to allow PDF files.fileSize
limit of 1MB.Solutions:
'application/pdf'
to the list of allowed mimetype
s in the fileFilter
function.fileSize
limit of 1MB, change the limits
option to { fileSize: 1024 * 1024 }
.upload.array('files')
instead of upload.single('file')
. The 'files' field should contain an array of files.