File Uploads, Downloads, and Static Assets
🎯 Introduction
By the end of this article, you will be able to receive form uploads, return download locations, and configure static access for public files.
📤 Receive uploaded files with Multer
Browser FormData uploads use multipart/form-data. Express projects commonly use Multer to parse its files and fields, exposing the uploaded file through req.file.
Install the dependency for this section:
npm install multer@2.5.0
Create files-app.mjs and prepare the upload directory:
import express from 'express';
import multer from 'multer';
import { fileURLToPath } from 'node:url';
export const app = express();
const uploadDir = fileURLToPath(new URL('./uploads/', import.meta.url));
The directory is fixed relative to the module rather than the terminal's working directory. Keep uploads separate from source code and configuration.
📏 Configure the destination and size limit
Continue configuring Multer:
const upload = multer({
dest: uploadDir,
limits: { fileSize: 1024 * 1024, files: 1, fields: 0 }
});
dest sets the storage directory, and Multer generates stored filenames. fileSize limits each file to 1 MiB, files allows one file, and fields: 0 rejects additional text fields.
Disk storage avoids retaining whole files in memory for extended periods. Multer reports oversized files as errors, which we convert to 413 below.
📥 Read file information in the route
Add an upload endpoint:
app.post('/files', upload.single('file'), (req, res) => {
if (!req.file) return res.status(400).json({ error: 'Select a file' });
res.status(201).json({
data: { id: req.file.filename, size: req.file.size }
});
});
single('file') requires the form file field to be named file. After parsing, req.file.filename is the server-generated filename and size is the byte count. Return 201 with these values so clients download by id rather than a user-supplied filename.
This example stores files as attachments and does not execute their contents. Image-only features must also verify actual format, dimensions, and content instead of trusting the client's MIME declaration.
📤 Download by file ID
Add a download endpoint:
app.get('/files/:id', (req, res, next) => {
if (!/^[a-f0-9]{32}$/.test(req.params.id)) {
return res.status(400).json({ error: 'Invalid file ID' });
}
res.download(req.params.id, 'download.bin', { root: uploadDir }, error => {
if (error) next(error);
});
});
This Multer version generates 32-character hexadecimal filenames by default. After validating id, res.download serves only from uploadDir and sets headers suggesting a download, using the fixed display name download.bin. Errors go to error middleware.
Private files require authentication and a database ownership check before download. Random filenames do not replace authorization.
🖼 Expose a designated directory with static middleware
Create public/readme.txt containing public demo in the example directory. Add the static directory:
const publicDir = fileURLToPath(new URL('./public/', import.meta.url));
app.use('/static', express.static(publicDir, { dotfiles: 'deny' }));
Visiting /static/readme.txt returns the text. Everything in this directory is public, so keep private uploads, .env, and source files elsewhere. Keep upload and static directories separate.
🧯 Handle upload and download failures
Place error middleware after the routes:
app.use((error, req, res, next) => {
if (res.headersSent) return next(error);
if (error.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({ error: 'File exceeds 1 MiB' });
}
if (error instanceof multer.MulterError) return res.status(400).json({ error: 'Invalid upload format' });
if (error.code === 'ENOENT') return res.status(404).json({ error: 'File not found' });
console.error(error);
res.status(500).json({ error: 'File processing failed' });
});
Wrong field names, extra files, and similar upload errors return 400; oversized files return 413; missing files return 404. Once transmission starts, JSON cannot be sent again; let the framework close the connection.
🧪 Upload and then download the file
Create the startup file:
import { app } from './files-app.mjs';
app.listen(3000, '127.0.0.1');
Run node files-server.mjs, prepare a small note.txt, and send:
curl -i http://127.0.0.1:3000/files -F 'file=@note.txt'
-F sends a form file whose field name is file, matching Multer's configuration. After receiving 201, download using the returned id:
curl http://127.0.0.1:3000/files/replace-with-actual-id -o downloaded.txt
The downloaded content should match the original. Browser FormData must also use the file field. Let the browser set Content-Type with the multipart boundary rather than setting this header manually.
❓ Questions and Answers
Q1: Can express.json parse file forms?
No. It handles JSON; Multer handles multipart file forms.
Q2: Is an individual file size limit sufficient?
Also limit upload frequency and per-user storage, and clean up abandoned files to prevent many small files from filling the disk.
Q3: Why not use the uploaded filename as the storage path?
It comes from the client and may collide or contain path information. Generate stored names on the server and use the original name only as validated display information.
🧪 Practice
Upload two files with the same name and confirm different stored IDs. Upload a file larger than 1 MiB and confirm 413.
// Record your results here
