Introduction
Image upload is a common feature in modern web applications. Websites often allow users to upload profile pictures, product photos, gallery images, blog thumbnails, and other visual content.
Node.js makes it possible to build image-upload functionality using Express.js and Multer. Multer handles files submitted through HTML forms, while Express processes the upload request and returns a response to the user.
However, image uploads require additional care because a file with a .jpg or .png extension is not necessarily a valid image. Applications should validate uploaded content, restrict file sizes, and store images safely.
What Is Image Upload in Node.js?
Image upload in Node.js is the process of receiving an image from a client, such as a web browser, and storing or processing it on the server.
For example, when a user uploads a profile picture, the browser sends the image to a Node.js application. The application receives the request, checks the upload, and stores the image in a configured location or a cloud storage service.
Common use cases include:
- Uploading profile pictures.
- Adding product images to an e-commerce website.
- Uploading images for blog posts.
- Creating photo galleries.
- Uploading images for news articles and social media posts.
What Is Multer in Node.js?
Multer is middleware for Express.js that handles multipart/form-data requests. This encoding type is commonly used when an HTML form sends files to a server.
Multer provides several useful features:
- Receiving single or multiple image files.
- Storing files on disk or in memory.
- Setting file size limits.
- Filtering uploads based on file properties.
- Providing information about uploaded files through the request object.
For a basic image-upload feature, we can use Multer’s diskStorage() method to save images to a folder on the server.
Prerequisites
Before starting this tutorial, make sure you have:
- Node.js installed on your computer.
- npm installed.
- Basic knowledge of JavaScript.
- Basic knowledge of Express.js and HTML forms.
Step 1: Create a Node.js Project
Create a new project directory and open it in your terminal.
mkdir node-image-upload
cd node-image-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, and Multer will process uploaded image files.
Step 2: Create the Project Structure
Create an app.js file and an index.html file. The application will use an uploads directory to store images.
node-image-upload/
├── uploads/
├── app.js
├── index.html
├── package.json
├── package-lock.json
└── node_modules/
The application code will create the uploads directory automatically if it does not exist.
Step 3: Create an HTML Image 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>Image Upload in Node.js</title>
</head>
<body>
<h1>Upload an Image</h1>
<form
action="/upload"
method="POST"
enctype="multipart/form-data"
>
<label for="image">Select an image:</label>
<input
type="file"
id="image"
name="image"
accept="image/jpeg,image/png,image/webp"
required
>
<button type="submit">Upload Image</button>
</form>
</body>
</html>
Let’s understand the important attributes.
| Property | Description |
|---|---|
| req.file | Contains information about a single uploaded file |
| req.files | Contains information about multiple uploaded files |
| req.file.originalname | Original filename supplied by the client |
| req.file.filename | Name used to store the file |
| req.file.mimetype | MIME type reported by the client |
| req.file.size | Uploaded file size in bytes |
| req.file.path | Storage path for a file saved on disk |
The accept attribute improves the file selection experience, but it is not a security feature. The server must validate uploaded files independently.
Step 4: Configure Multer for Image Uploads
Create the 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');
fs.mkdirSync(uploadDir, { recursive: true });
const allowedExtensions = new Set([
'.jpg',
'.jpeg',
'.png',
'.webp'
]);
const allowedMimeTypes = new Set([
'image/jpeg',
'image/png',
'image/webp'
]);
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}`);
}
});
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 WebP images are allowed.'));
};
const upload = multer({
storage: storage,
limits: {
fileSize: 3 * 1024 * 1024,
files: 1
},
fileFilter: fileFilter
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/upload', upload.single('image'), (req, res) => {
if (!req.file) {
return res.status(400).send('Please select an image to upload.');
}
res.send(`
<h2>Image uploaded successfully!</h2>
<p>Stored filename: ${req.file.filename}</p>
<p>Image size: ${req.file.size} bytes</p>
<a href="/">Upload another image</a>
`);
});
app.use((err, req, res, next) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).send(
'Image size must not exceed 3 MiB.'
);
}
if (err.code === 'LIMIT_UNEXPECTED_FILE') {
return res.status(400).send(
'Unexpected image field or too many files.'
);
}
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 example configures Multer to accept one image with a maximum size of 3 MiB. It allows JPG, JPEG, PNG, and WebP filenames when their reported MIME types match the configured list.
The filename is generated using randomUUID() to reduce filename collisions and avoid using the original filename directly as a storage path.
Important: The fileFilter above performs basic checks using the extension and MIME type reported by the client. These values can be spoofed, so this code alone does not prove that a file contains valid image data. Production applications should inspect the actual file content before trusting or serving uploaded images.
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 WebP image smaller than 3 MiB, then click Upload Image.
If the upload succeeds, the application displays a success message and stores the image in the uploads directory with its generated filename.
Step 6: Understand upload.single()
The following Multer method handles one image upload:
app.post('/upload', upload.single('image'), (req, res) => {
console.log(req.file);
res.send('Image received successfully.');
});
The upload.single(‘image’) method accepts one file from the form field named image.
After the upload is processed, Multer makes the uploaded file information available through req.file.
Some useful properties include:
These properties can be used to save image metadata in a database or display upload information to the user.
Step 7: Display the Uploaded Image
After uploading an image, you may want to display it in the browser. In a simple learning project, you can create a separate route to serve images from the upload directory.
For example:
app.get('/images/:filename', (req, res, next) => {
const filename = req.params.filename;
// Accept only generated UUID filenames with allowed extensions.
if (
!/^[0-9a-f-]{36}\.(jpg|jpeg|png|webp)$/i.test(filename)
) {
return res.status(400).send('Invalid image filename.');
}
res.sendFile(
filename,
{
root: uploadDir,
dotfiles: 'deny'
},
(err) => {
if (err) next(err);
}
);
});
After adding this route, you can display an uploaded image using its stored filename:
<img
src="/images/your-generated-filename.png"
alt="Uploaded image"
width="300"
>
Replace the example filename with the actual generated filename returned by the upload process.
| Property | Description |
|---|---|
| req.file.originalname | Original filename supplied by the client |
| req.file.filename | Generated filename used for storage |
| req.file.mimetype | MIME type reported by the client |
| req.file.size | Uploaded file size in bytes |
| req.file.path | Storage path for a file saved on disk |
This route is suitable only for images intended to be publicly accessible. For private images, use an authenticated route that checks whether the current user is authorized to view the file.
Step 8: Validate Images More Carefully
Validating the extension and MIME type is a useful first step, but it is not sufficient for a production application.
For stronger validation, consider these practices:
- Inspect the actual file content with a trusted image-processing library.
- Reject files that cannot be decoded as valid images.
- Restrict image dimensions and total pixel count to reduce resource-exhaustion risks.
- Re-encode accepted images into a known format when appropriate.
- Remove temporary files if validation fails.
- Keep sensitive or unverified uploads private until validation is complete.
For example, an image-processing library can read the image metadata and reject files that are not valid supported images. The exact implementation depends on the library and your application’s requirements.
Common Mistakes When Uploading Images
1. Forgetting multipart/form-data
If the form does not include enctype=”multipart/form-data”, Multer will not receive the file in the expected format.
Solution: Add the correct enctype attribute to the form.
2. Using Different Field Names
If the HTML input uses name=”image” but the server uses upload.single(‘photo’), Multer may reject the request.
Solution: Use the same field name in the HTML form and Multer configuration.
3. Accepting Images of Any Size
Large image files can consume server storage and processing resources.
Solution: Configure a suitable file size limit and consider limiting image dimensions.
4. Trusting the File Extension
A file named photo.jpg might not contain a valid JPEG image.
Solution: Validate the actual image content instead of relying only on the extension.
5. Using the Original Filename as the Storage Path
Client-provided filenames can contain unexpected characters and may create naming conflicts.
Solution: Generate a safe filename on the server.
6. Exposing Private Images
Profile images may be public, but identity documents and other sensitive images may need restricted access.
Solution: Store private images outside publicly accessible directories and enforce authorization when serving them.
Security Best Practices for Image Uploads
When implementing image upload in a real application, follow these practices:
- Restrict image formats: Allow only the formats your application needs.
- Validate file content: Check that the uploaded data is a valid image.
- Set file size limits: Prevent excessively large uploads.
- Limit image dimensions: Protect against images with extremely large pixel counts.
- Generate unique filenames: Avoid unsafe paths and filename collisions.
- Keep private files protected: Do not expose sensitive images through public URLs.
- Use authentication where required: Limit upload access to authorized users.
- Monitor storage usage: Prevent repeated uploads from exhausting disk space.
- Clean up rejected uploads: Remove files that fail validation.
- Consider image processing or cloud storage: Resize, compress, or store images using services suited to your application’s needs.
The example in this article is intended for learning. Production applications should add content validation, access controls, monitoring, and any additional protections required by the type of images they accept.
Conclusion
Image upload is an important feature in many Node.js applications. By combining Express.js and Multer, you can receive image files from a browser, validate basic file properties, and store images on the server.
In this tutorial, you learned how to create an image upload form, configure Multer, restrict file types and sizes, access uploaded file information, display stored images, and apply security best practices.