- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js File Uploads
File uploads are a common feature in web applications, enabling users to upload documents, images, or other files to the server. Express.js provides a simple way to handle file uploads using middleware like multer
.
Key Features of File Uploads
- Efficient Parsing: Middleware like
multer
efficiently parses multipart form data. - Storage Options: Files can be stored locally or on cloud services.
- File Validation: Supports validating file types, sizes, and other properties.
- Custom Destinations: Easily configure where files are stored.
Setting Up File Uploads in Express.js
Install multer
Middlewaremulter
is a popular middleware for handling file uploads in Node.js.
npm install multer
Basic Configuration
Configure multer
to specify storage and file-handling options.
Example:
const multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // Directory for storing files
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`); // Unique file name
}
});
const upload = multer({ storage });
Handling Single File Upload
Use upload.single()
for uploading a single file.
Example:
app.post('/upload', upload.single('file'), (req, res) => {
res.send(`File uploaded successfully: ${req.file.filename}`);
});
Handling Multiple File Uploads
Use upload.array()
for handling multiple files.
Example:
app.post('/upload-multiple', upload.array('files', 5), (req, res) => {
res.send(`${req.files.length} files uploaded successfully.`);
});
Validating Uploaded Files
Add validation for file types and sizes.
Example:
const uploadWithValidation = multer({
storage,
fileFilter: (req, file, cb) => {
if (!file.mimetype.startsWith('image/')) {
return cb(new Error('Only image files are allowed'), false);
}
cb(null, true);
},
limits: { fileSize: 1 * 1024 * 1024 } // 1MB limit
});
Serving Uploaded Files
Serve uploaded files as static resources.
Example:
app.use('/uploads', express.static('uploads'));
Complete Example
const express = require('express');
const multer = require('multer');
const app = express();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
}
});
const upload = multer({ storage });
app.post('/upload', upload.single('file'), (req, res) => {
res.send(`File uploaded: ${req.file.filename}`);
});
app.post('/upload-multiple', upload.array('files', 5), (req, res) => {
res.send(`Uploaded ${req.files.length} files.`);
});
app.use('/uploads', express.static('uploads'));
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Summary
Express.js simplifies file uploads using middleware like multer
. It provides robust support for single and multiple file uploads with configurable storage, validation, and error handling, making it ideal for web applications requiring file management.