When it comes to uploading files in Node.js, the express-fileupload middleware and multer are some of the popular options that help simplify file uploading. Here’s a short tutorial for every one of them:
1. Using express-fileupload Uploading Files in Node.js
First, install the express-fileupload
package:
$ npm install express express-fileupload
Next, set up a basic server to handle file uploads:
const express = require("express");
const fileUpload = require("express-fileupload");
const app = express();
// Enable files upload
app.use(fileUpload());
// Upload endpoint
app.post("/upload", (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
// Access the file
let sampleFile = req.files.sampleFile;
// Move the file to a desired location
sampleFile.mv(`./uploads/${sampleFile.name}`, (err) => {
if (err) return res.status(500).send(err);
res.send("File uploaded!");
});
});
app.listen(3000, () => {
console.log("Server started on http://localhost:3000");
});
req.files.sampleFile
accesses the uploaded file (wheresampleFile
is the name attribute in the HTML form).sampleFile.mv
moves the file to a specific directory.
2. Using multer
For more advanced file-handling options (e.g., file filtering, storage management), multer
is a robust choice.
Install multer
:
$ npm install express multer
Set up an upload handler with multer
:
const express = require("express");
const multer = require("multer");
const app = express();
// Set storage engine
const storage = multer.diskStorage({
destination: "./uploads",
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
},
});
// Init upload
const upload = multer({ storage: storage }).single("file");
// Upload endpoint
app.post("/upload", (req, res) => {
upload(req, res, (err) => {
if (err) {
return res.status(500).send(err.message);
}
res.send("File uploaded successfully!");
});
});
app.listen(3000, () => {
console.log("Server started on http://localhost:3000");
});
multer.diskStorage
configures where and how the file will be stored.upload.single("file")
tellsmulter
to handle a single file upload, where"file"
is the form’sname
attribute.
Basic HTML Form for Uploading
To test either example, use a simple HTML form like this:
<!DOCTYPE html>
<html lang="en">
<head><title>File Upload</title></head>
<body>
<form ref="uploadForm" id="uploadForm" action="http://localhost:3000/upload" method="post" encType="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload!" />
</form>
</body>
</html>
Each approach is effective; express-fileupload
is simpler, while multer
provides more flexibility for customization.
Leave a Reply