Node.js Files Upload using Multer package
Another useful NPM module that is capable of handling file uploads is called Multer. Users can upload either single or multiple files at a time.
To install, use the following command
npm install multer
In the beginning of an Express app, include muletr and declare the Multer object.
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
Assuming that you have a route to handle a GET request and display a multipart HTML form that posts the form to /upload route, add the following function to handle POST request −
app.post("/upload", upload.single("myFile"), (req, res) => {
console.log("Body: ", req.body);
console.log("File: ", req.file);
res.send("File successfully uploaded.");
});
To store the uploaded file at a specified location instead of the default location of the temporary file, configure the Multer location as below −
var storage = multer.diskStorage({
destination: function(req, file, cb) {
// destination is used to specify the path of the directory in which the files have to be stored
cb(null, './uploads');
},
filename: function (req, file, cb) {
// It is the filename that is given to the saved file.
cb(null , file.originalname);
}
});
// Configure storage engine instead of dest object.
const upload = multer({ storage: storage })
Complete Example
const express = require("express");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const app = express();
const PORT = 3000;
// Ensure the uploads directory exists
const uploadDir = "./uploads";
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
// Configure Multer storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
// Specify the directory where files will be saved
cb(null, uploadDir);
},
filename: function (req, file, cb) {
// Save the file with its original name
cb(null, file.originalname);
},
});
// Initialize Multer with the configured storage
const upload = multer({ storage });
// Middleware to parse incoming form data
app.use(express.urlencoded({ extended: true }));
// Serve an HTML form for file upload
app.get("/", (req, res) => {
res.send(`
<h2>Upload Files</h2>
<form action="/upload-single" method="post" enctype="multipart/form-data">
<label for="singleFile">Upload Single File:</label><br />
<input type="file" name="singleFile" id="singleFile" /><br /><br />
<button type="submit">Upload Single File</button>
</form>
<br />
<form action="/upload-multiple" method="post" enctype="multipart/form-data">
<label for="multiFiles">Upload Multiple Files:</label><br />
<input type="file" name="multiFiles" id="multiFiles" multiple /><br /><br />
<button type="submit">Upload Multiple Files</button>
</form>
`);
});
// Handle single file upload
app.post("/upload-single", upload.single("singleFile"), (req, res) => {
console.log("Body:", req.body);
console.log("File:", req.file);
res.send(`Single file uploaded: <a href="/uploads/${req.file.filename}" target="_blank">${req.file.originalname}</a>`);
});
// Handle multiple file uploads
app.post("/upload-multiple", upload.array("multiFiles", 10), (req, res) => {
console.log("Body:", req.body);
console.log("Files:", req.files);
const fileLinks = req.files
.map(file => `<a href="/uploads/${file.filename}" target="_blank">${file.originalname}</a>`)
.join("<br />");
res.send(`Multiple files uploaded:<br />${fileLinks}`);
});
// Serve uploaded files statically
app.use("/uploads", express.static(uploadDir));
// Start the server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Output
Terminal commands and logs
D:\React_Project\NodeProject> node MulterExampleForFileUpload.js
node:internal/modules/cjs/loader:1252
throw err;
^
Error: Cannot find module 'multer'
Require stack:
- D:\React_Project\NodeProject\MulterExampleForFileUpload.js
at Function._resolveFilename (node:internal/modules/cjs/loader:1249:15)
at Function._load (node:internal/modules/cjs/loader:1075:27)
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:218:24)
at Module.require (node:internal/modules/cjs/loader:1340:12)
at require (node:internal/modules/helpers:141:16)
at Object.<anonymous> (D:\React_Project\NodeProject\MulterExampleForFileUpload.js:2:16)
at Module._compile (node:internal/modules/cjs/loader:1546:14)
at Object..js (node:internal/modules/cjs/loader:1689:10)
at Module.load (node:internal/modules/cjs/loader:1318:32) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'D:\\React_Project\\NodeProject\\MulterExampleForFileUpload.js' ]
}
Node.js v22.11.0
PS D:\React_Project\NodeProject> npm install multer
added 19 packages, and audited 91 packages in 2s
15 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
PS D:\React_Project\NodeProject> node MulterExampleForFileUpload.js
Server running at http://localhost:3000
Body: [Object: null prototype] {}
File: {
fieldname: 'singleFile',
originalname: 'buttons_touchopacity.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './uploads',
filename: 'buttons_touchopacity.jpg',
path: 'uploads\\buttons_touchopacity.jpg',
size: 20502
}
Body: [Object: null prototype] {}
Files: [
{
fieldname: 'multiFiles',
originalname: 'buttons_redbutton.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './uploads',
filename: 'buttons_redbutton.jpg',
path: 'uploads\\buttons_redbutton.jpg',
size: 21981
},
{
fieldname: 'multiFiles',
originalname: 'network_images.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './uploads',
filename: 'network_images.jpg',
path: 'uploads\\network_images.jpg',
size: 25286
}
]
Recent Comments