Node.js File Upload with Multer and Express: A Step-by-Step Guide
Node.js is a popular runtime environment for building server-side applications. One common task in web development is to handle file uploads, such as images or documents. In this article, we will walk through the process of implementing file uploads in a Node.js application using the Multer middleware and Express framework.
Step 1: Set up a Node.js project
First, make sure you have Node.js and npm installed on your system. If not, you can download and install them from the official website.
Next, create a new directory for your project and run the following command in your terminal to initialize a new Node.js project:
npm init -y
Step 2: Install Multer and Express
Now, install the Multer middleware and Express framework by running the following command in your terminal:
npm install multer express
Step 3: Create an Express server
Create a new file called app.js
and add the following code to create a basic Express server:
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Step 4: Set up file upload with Multer
Add the following code to app.js
to set up file upload using Multer:
const multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now());
}
});
const upload = multer({ storage: storage });
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully');
});
Step 5: Create an HTML form for file upload
Create a new file called index.html
and add the following code to create a simple HTML form for file upload:
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
Step 6: Run the Express server
Finally, run the following command in your terminal to start the Express server:
node app.js
Visit http://localhost:3000
in your web browser and you should see the file upload form. Choose a file and click the upload button to test the file upload functionality.
Congratulations! You have successfully implemented file upload in a Node.js application using Multer and Express.
Watch this video on 720 for better quality 👍.
How do I upload multiple files from different inputs like video and images even documents files
How can deploy on vercel server?
the image i upload showing undefined in vs code