Uploading multiple files lets users send many files at once. This saves time and makes apps easier to use.
0
0
Multiple file uploads in Express
Introduction
When users need to upload several photos to a profile or gallery.
When submitting multiple documents in a form, like resumes and cover letters.
When allowing batch uploads for product images in an online store.
When users want to upload multiple attachments in a messaging app.
When collecting multiple files for a project submission or report.
Syntax
Express
const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.array('files', 10), (req, res) => { // req.files contains array of uploaded files res.send('Files uploaded'); });
upload.array(fieldname, maxCount) handles multiple files from the same field.
The req.files array holds info about each uploaded file.
Examples
Uploads up to 5 files from the form field named 'photos'.
Express
app.post('/photos/upload', upload.array('photos', 5), (req, res) => { res.send(`Uploaded ${req.files.length} photos.`); });
Uploads any number of files from the 'documents' field (no max limit).
Express
app.post('/docs/upload', upload.array('documents'), (req, res) => { res.send(`Received ${req.files.length} documents.`); });
Sample Program
This Express app uses multer to accept up to 3 files from the 'files' field. It responds with how many files were uploaded or an error if none.
Express
const express = require('express'); const multer = require('multer'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.array('files', 3), (req, res) => { if (!req.files || req.files.length === 0) { return res.status(400).send('No files uploaded.'); } res.send(`Uploaded ${req.files.length} files.`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Make sure the HTML form uses enctype="multipart/form-data" to send files correctly.
Files are saved temporarily in the 'uploads/' folder; you can customize storage options.
Always validate file types and sizes for security.
Summary
Use upload.array() from multer to handle multiple file uploads in Express.
The uploaded files are available as an array in req.files.
Set a max count to limit how many files users can upload at once.