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 Middleware
multer 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.