- Install Multer: Open your terminal and navigate to your project’s directory. Run the following command to install Multer via npm:
npm install multer, express
- Set up the Multer middleware: In your Node.js application file (e.g.,
app.js
orindex.js
), require the necessary dependencies:
const express = require('express');
const multer = require('multer');
const app = express();
const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/'); }, filename: function (req, file, cb) { cb(null, file.originalname); } }); const upload = multer({ storage: storage });
- Set up the route: Create an endpoint that will handle the file upload. Use the
upload
middleware created in the previous step:
app.post('/upload', upload.single('file'), (req, res) => { // Handle the uploaded file here // `req.file` contains the file details res.send('File uploaded successfully.'); });
In the example above, we use the upload.single('file')
middleware to handle a single file upload. The parameter 'file'
should match the name attribute of the file input field in your HTML form.
- Start the server: Finally, start the server to listen for incoming requests:
app.listen(3000, () => { console.log('Server is running on port 3000'); });
That’s it! You now have a basic setup for file uploads using Multer in Node.js. Remember to create an uploads/
directory in your project to store the uploaded files.
Leave a Reply