File Uploads and Serving Static Files
Let users send files to your server, and send files back without exhausting memory
- serve a folder of assets with
express.static, - explain what
multipart/form-datais and whyexpress.json()cannot read it, - receive single and multiple uploads with multer (disk vs memory storage),
- send files back with
res.sendFile,res.download, and a stream.
1. Serving static files with express.static
A static file is one the server sends back unchanged: an image, a CSS file, a font, a downloadable PDF. You do not want to write a route for every one of them. Express ships a built-in middleware, express.static, that maps a folder on disk to URLs automatically.
const express = require('express');
const path = require('path');
const app = express();
// Serve every file inside ./public at the site root
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
Now a file at public/logo.png is reachable at http://localhost:3000/logo.png with no route of your own. Express also sets the correct Content-Type, supports caching headers, and answers HTTP range requests for you.
Often you want assets under a URL prefix so they do not collide with your API routes. Pass a mount path as the first argument:
// Mount the same folder under a URL prefix
app.use('/static', express.static('public'));
// public/logo.png -> http://localhost:3000/static/logo.png
// public/css/app.css -> http://localhost:3000/static/css/app.css
express.static at your project root, or you would hand out your source code and node_modules.