Introduction
File upload is a common feature in modern web applications. Users may need to upload profile pictures, documents, PDFs, product images, resumes, or other files to a website.
Node.js allows developers to build file-upload functionality using frameworks such as Express.js and middleware such as Multer. Multer helps handle files sent through HTML forms using the multipart/form-data encoding type.
What Is File Upload in Node.js?
File upload in Node.js is the process of receiving files from a client, such as a web browser, and saving or processing them on the server.
For example, when a user selects a profile picture and clicks the Upload button, the browser sends the file to the server. The Node.js application receives the request, validates the file, and stores it or sends it to a storage service.
Common file-upload use cases include:
- Uploading profile pictures.
- Uploading resumes and PDF documents.
- Adding product images to an e-commerce website.
- Uploading reports and other business documents.
- Importing CSV or Excel files into an application.
What Is Multer in Node.js?
Multer is middleware for Express.js that handles multipart/form-data requests, which are commonly used for file uploads.
It helps developers access uploaded files through the request object and configure where the files should be stored.
Important Multer features include:
- Handling single and multiple file uploads.
- Storing files in memory or on disk.
- Setting file size and file count limits.
- Filtering files based on their properties.
- Providing information about uploaded files.
To use Multer, you first need to install Express and Multer in your Node.js project.
Prerequisites
Before implementing file upload, make sure you have:
- Node.js installed on your computer.
- npm available in your terminal.
- Basic knowledge of JavaScript and Node.js.
- Basic knowledge of Express.js and HTML forms.
Step 1: Create a Node.js Project
Create a new directory for your project and move into it.
mkdir node-file-upload
cd node-file-upload
npm init -y
The npm init -y command creates a package.json file with default project settings.
Next, install Express and Multer:
npm install express multer
Express will handle HTTP requests, while Multer will process uploaded files.
Step 2: Create the Project Structure
Create an app.js file and an index.html file.
Your project structure should look like this:
node-file-upload/
├── uploads/
├── app.js
├── index.html
├── package.json
├── package-lock.json
└── node_modules/
The uploads directory will store the uploaded files in this example. Create it before running the application.
Step 3: Create the HTML File Upload Form
Create an index.html file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload with Node.js</title>
</head>
<body>
<h1>Upload a File</h1>
<form
action="/upload"
method="POST"
enctype="multipart/form-data"
>
<label for="file">Select a file:</label>
<input
type="file"
id="file"
name="file"
required
>
<button type="submit">Upload File</button>
</form>
</body>
</html>
Let’s understand the important parts of this form.
| Attribute | Purpose |
|---|---|
action="/upload" |
Sends the form data to the /upload route. |
method="POST" |
Sends the file using an HTTP POST request. |
enctype="multipart/form-data" |
Allows the form to send file data. |
type="file" |
Displays a file selection control. |
name="file" |
Identifies the uploaded file in the request. |
The name=”file” attribute is important because the Multer middleware will use the same field name to receive the file.
Step 4: Configure Multer in Node.js
Create an app.js file and add the following code:
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { randomUUID } = require('crypto');
const app = express();
const PORT = 3000;
const uploadDir = path.join(__dirname, 'uploads');
// Create the upload directory if it does not exist.
fs.mkdirSync(uploadDir, { recursive: true });
// Configure where uploaded files will be stored.
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDir);
},
filename: (req, file, cb) => {
const extension = path.extname(file.originalname).toLowerCase();
cb(null, `randomUUID(){extension}`);
}
});
// Allow only selected file types.
const allowedExtensions = new Set([
'.jpg',
'.jpeg',
'.png',
'.pdf'
]);
const allowedMimeTypes = new Set([
'image/jpeg',
'image/png',
'application/pdf'
]);
const fileFilter = (req, file, cb) => {
const extension = path.extname(file.originalname).toLowerCase();
if (
allowedExtensions.has(extension) &&
allowedMimeTypes.has(file.mimetype)
) {
return cb(null, true);
}
cb(new Error('Only JPG, PNG, and PDF files are allowed.'));
};
// Configure Multer.
const upload = multer({
storage: storage,
limits: {
fileSize: 5 * 1024 * 1024
},
fileFilter: fileFilter
});
// Serve the HTML form.
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Handle the uploaded file.
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('Please select a file to upload.');
}
res.send(`
File uploaded successfully!
Saved file name: ${req.file.filename}
File size: ${req.file.size} bytes
Upload another file
`);
});
// Handle Multer and other upload errors.
app.use((err, req, res, next) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).send('File size must not exceed 5 MB.');
}
return res.status(400).send(`Upload error: ${err.message}`);
}
if (err) {
return res.status(400).send(`Upload failed: ${err.message}`);
}
next();
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
This code configures Multer to store files in the uploads directory. It also limits uploads to 5 MB and permits files with JPG, JPEG, PNG, and PDF extensions when their reported MIME types match the configured list.
Important: Checking the filename extension and reported MIME type is only a basic filter. These values can be spoofed, so production applications should verify file content and apply additional security controls.
Step 5: Run the Node.js Application
Open your terminal in the project directory and run:
node app.js
You should see a message similar to:
Server running at http://localhost:3000
Open the following address in your browser:
http://localhost:3000
Select a JPG, PNG, or PDF file that is smaller than 5 MB, then click Upload File.
If the upload succeeds, the server will display a success message. The uploaded file will be saved in the uploads directory with a generated filename.
Step 6: Understand How the File Upload Works
The complete upload process follows these steps:
- The user opens the upload page in a browser.
- The user selects a file using the HTML file input.
- The browser sends the file to the /upload route using a POST request.
- Multer processes the multipart/form-data request.
- Multer checks the configured file size limit and file filter.
- The file is saved in the uploads directory.
- The Express route sends a response to the browser.
This workflow separates the frontend form from the server-side file handling logic.
Upload a Single File Using Multer
In the example above, the following middleware handles a single file:
app.post('/upload', upload.single('file'), (req, res) => {
console.log(req.file);
res.send('File received successfully.');
});
The upload.single(‘file’) method accepts one uploaded file from the form field named file.
| Property | Description |
|---|---|
| req.file.originalname | Original filename supplied by the client |
| req.file.filename | Filename used to store the file |
| req.file.mimetype | MIME type reported by the client |
| req.file.size | Size of the uploaded file in bytes |
| req.file.path | Path where the uploaded file was stored |
After successful processing, Multer makes the file information available through req.file.
Some useful properties include:
These properties are useful when logging upload details or saving file metadata in a database.
How to Upload Multiple Files in Node.js
Multer also supports multiple files. To accept multiple files from the same form field, use upload.array().
For example:
app.post('/upload-multiple', upload.array('files', 3), (req, res) => {
res.send(`${req.files.length} file(s) uploaded successfully.`);
});
The second argument, 3, limits the number of files accepted by this middleware to three.
The HTML form must use the same field name and include the multiple attribute:
<form
action="/upload-multiple"
method="POST"
enctype="multipart/form-data"
>
<input type="file" name="files" multiple required>
<button type="submit">Upload Files</button>
</form>
This example uses the same Multer configuration, so the file size and file type restrictions still apply.
Common Mistakes When Uploading Files
1. Forgetting multipart/form-data
If the form does not include enctype=”multipart/form-data”, the browser will not send the file in the expected format.
Solution: Add the correct enctype attribute to the HTML form.
2. Using Different Field Names
If the HTML input uses name=”file” but the server uses upload.single(‘image’), Multer will reject the unexpected field.
Solution: Keep the form field name and Multer field name consistent.
3. Not Creating the Upload Directory
If the configured destination directory does not exist or cannot be written to, the upload can fail.
Solution: Create the directory before accepting uploads and ensure the application has the necessary permissions.
4. Allowing Files of Any Size
Large uploads can consume server resources and affect application performance.
Solution: Set appropriate file size and file count limits.
5. Trusting the File Extension
A filename ending in .pdf or .jpg does not prove that the file contains valid PDF or image data.
Solution: Validate file content where appropriate and use additional security checks.
6. Making Uploaded Files Public by Accident
Files saved on the server should not automatically be available for public access unless that is the intended behavior.
Solution: Store private documents outside publicly served directories and provide authorized download routes when necessary.
Security Best Practices for File Uploads
File uploads can introduce security and resource-management risks. Follow these practices when building a production application.
- Validate file content: Do not rely only on the extension or client-supplied MIME type.
- Limit file sizes: Configure appropriate limits based on the application’s needs.
- Generate safe filenames: Avoid using client-provided filenames directly as storage paths.
- Restrict allowed file types: Accept only the formats required by the application.
- Require authentication when needed: Only authorized users should upload files to protected areas.
- Control file access: Keep sensitive uploads private and check permissions before allowing downloads.
- Scan potentially dangerous files: Use malware scanning when appropriate for the application.
- Use suitable storage: Consider object storage or another dedicated storage service for larger applications.
- Protect the application from excessive uploads: Apply request limits, rate limits, monitoring, and appropriate cleanup policies.
The sample code demonstrates a basic upload feature, not a complete production security solution. Additional controls should be implemented according to the type of files and the sensitivity of the application.
Conclusion
File upload is an important feature in many Node.js applications. With Express and Multer, you can receive files from an HTML form, validate basic file properties, and save the files on the server.
In this tutorial, you learned how to create a Node.js project, configure Multer, upload a single file, handle multiple files, manage upload errors, and apply basic security practices.