Express.js / File Uploads and Multer in Express.js
Validating File Formats and Sizes
This tutorial will teach you how to validate file formats and sizes using Multer in Express.js. We'll look at the different options provided by Multer for validation, and how to u…
Section overview
5 resourcesExplores handling file uploads using Multer in Express applications.
1. Introduction
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.
2. Step-by-Step Guide
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.
3. Code Examples
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:
- We import the required modules.
- We set up Multer to save uploaded files to the 'uploads' directory.
- We create an Express route for file upload. The
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:
- We define a custom storage option that includes a
fileFilter. - The
fileFilterfunction checks themimetypeof 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:
- We add a
limitsoption to the Multer configuration. - The
fileSizelimit is set to 5MB.
4. Summary
In this tutorial, we learned how to:
- Use Multer to handle file uploads in an Express.js app.
- Validate file formats and sizes using Multer's
fileFilterandlimitsoptions.
To continue learning, you can explore more about Multer's options, such as inMemoryStorage for storing the files in memory as Buffer objects.
5. Practice Exercises
- Modify the
fileFilterfunction to allow PDF files. - Set a
fileSizelimit of 1MB. - Create a route for uploading multiple files at once.
Solutions:
- To allow PDF files, add
'application/pdf'to the list of allowedmimetypes in thefileFilterfunction. - To set a
fileSizelimit of 1MB, change thelimitsoption to{ fileSize: 1024 * 1024 }. - To create a route for uploading multiple files, use
upload.array('files')instead ofupload.single('file'). The 'files' field should contain an array of files.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article