In this tutorial, we will learn how to upload files in Express.js using Multer in 2024. Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is easy to use and greatly simplifies the process of handling file uploads in your Express.js application.
To get started, you will need to have Node.js and Express.js installed on your machine. If you haven’t already installed Node.js, you can download it from the official website (https://nodejs.org/) and follow the installation instructions. Once you have Node.js installed, you can create a new Express.js project by running the following commands in your terminal:
npm install express-generator -g
express my-express-app
cd my-express-app
npm install
Next, you will need to install Multer in your Express.js project by running the following command in your terminal:
npm install multer
Now, let’s create a new route in your Express.js application for uploading files. Create a new file called upload.js
in the routes
directory of your project and add the following code:
const express = require('express');
const router = express.Router();
const multer = require('multer');
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 });
router.post('/', upload.single('file'), (req, res) => {
res.send('File uploaded successfully');
});
module.exports = router;
In this code snippet, we define a new route that handles file uploads using Multer. We create a new instance of Multer with a disk storage engine that specifies the destination directory for the uploaded files. We then define a route that accepts POST requests and uses the upload.single('file')
middleware to handle the file upload.
Next, let’s update the app.js
file in the root directory of your project to use the new route we just created. Add the following code to the app.js
file:
const uploadRouter = require('./routes/upload');
app.use('/upload', uploadRouter);
Now, you can start your Express.js server by running the following command in your terminal:
npm start
Your Express.js application is now ready to accept file uploads using Multer. To test the file upload functionality, you can use a tool like Postman to send a POST request to http://localhost:3000/upload
with a file attached in the request body.
That’s it! You have successfully learned how to upload files in Express.js using Multer in 2024. Multer makes it easy to handle file uploads in your Express.js application, allowing you to focus on building great features for your users. Happy coding! #Bunjs #Programming #Security #DataScience
Very informative