multer npm
- Install multer npm package:
npm install multer
- Import multer in your Express application:
javascript
const multer = require('multer');
- Set up multer storage configuration:
javascript
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/'); // Specify the destination folder for storing uploaded files
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname); // Set the filename to include the current timestamp
}
});
- Create a multer instance with the configured storage:
javascript
const upload = multer({ storage: storage });
- Define a route in your Express application where you want to handle file uploads:
```javascript app.post('/upload', upload.single('file'), function (req, res, next) { // 'file' is the name attribute of the file input field in your form // This middleware will process a single file upload
// Access uploaded file details using req.file
console.log('File uploaded:', req.file);
// Handle other form fields in req.body
console.log('Other form fields:', req.body);
// Send a response to the client
res.send('File uploaded successfully');
}); ```
- Create a form in your HTML file with the appropriate
enctype
attribute for file uploads:
```html
```
Start your Express application and navigate to the form page in a browser.
Select a file using the file input field and submit the form.
Check the console logs on the server side for information about the uploaded file.
Handle the uploaded file as needed in your application.