Certainly! Handling file uploads in Node.js using Multer middleware involves configuring Multer to manage multipart/form-data and save uploaded files to the server. Here's an example:
First, make sure you have Multer installed. If not, install it via npm:
npm install multer
Here's a basic example of handling file uploads using Multer in a Node.js/Express application:
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
// Set storage engine and destination
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/'); // Save uploaded files to the 'uploads' directory
},
filename: function (req, file, cb) {
// Rename the file if needed (here, I'm using the original filename)
cb(null, file.originalname);
}
});
// Initialize upload
const upload = multer({
storage: storage,
limits: { fileSize: 1000000 } // Limit file size if needed (here, it's 1MB)
}).single('myFile'); // 'myFile' should match the name attribute in your HTML form
// Endpoint to handle file upload
app.post('/upload', (req, res) => {
upload(req, res, (err) => {
if (err) {
// Handle errors during upload
res.status(400).send('Error uploading file!');
} else {
// File uploaded successfully
if (req.file === undefined) {
// No file selected
res.status(400).send('Error: No File Selected!');
} else {
// File details accessible via req.file object
res.send('File Uploaded!');
// Additional logic to handle the uploaded file
}
}
});
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
In this example:
- Multer's `diskStorage` is used to specify where uploaded files will be stored.
- The `upload` middleware is configured to handle a single file upload. Adjust `single('myFile')` to match the field name from your form.
- The `/upload` endpoint receives file uploads, checks for errors, and provides feedback on successful or unsuccessful uploads.
Ensure that you've created an HTML form on the client-side to handle file uploads, and the form's `enctype` attribute is set to `multipart/form-data` to allow file uploads. Adjust the endpoint (`/upload`) and form attributes according to your application's needs.