Welcome to this comprehensive guide on the multer Middleware in Node.js! This tutorial is designed to help both beginners and intermediate learners understand this powerful middleware for handling file uploads in Node.js applications.
Multer is a Node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It's essential for creating forms that can accept files in a Node.js application.
First, let's install multer using npm:
npm install multerHere's a basic example of using multer to handle file uploads:
const express = require('express');
const multer = require('multer');
const app = express();
// Set up multer storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
// Create multer upload object
const upload = multer({ storage: storage });
// Handle file uploads (POST /upload)
app.post('/upload', upload.single('myFile'), (req, res, next) => {
// req.file contains information of the uploaded file
// req.body will contain form data fields other than the file
// You can now save the file to a database or perform other operations
res.send('File uploaded successfully!');
});
// Start server
app.listen(3000, () => console.log('Server started on port 3000'));In this example, we've set up multer to store uploaded files in the uploads directory and given each file the original name. The file is uploaded to the server when a POST request is sent to /upload with the file attached as myFile.
upload.array() method.Which npm package do we use to handle file uploads in Node.js?