By Saheb Sutradhar - Updated On 13-03-2024
Multer is a Node.js middleware designed to handle multipart/form-data in forms. If you’ve ever dealt with file uploads in Node.js, you know it can be a bit of a headache. That’s where Multer comes to the rescue! In this article, we’ll explore what Multer is, how it works, and how to use it effectively.
Multer is like the trusty sidekick for handling file uploads in your Node.js applications. It’s similar to the popular body-parser middleware that’s built into Express for handling form submissions. However, Multer shines when it comes to processing multipart data, specifically multipart/form-data forms.
Here are the key points about Multer:
Let’s dive into some practical examples of how to use Multer:
Before diving into the code, you'll need to set up a Node.js project. If you haven't already, initialize a new Node.js project by running npm init
in your terminal and follow the prompts. Once your project is set up, you can install Multer using npm:
npm install multer
Let's create a simple Node.js application to demonstrate how to use Multer for file uploads. First, create a new JavaScript file, e.g., app.js
, and require the necessary modules:
const express = require('express');
const multer = require('multer');
const path = require('path');
Next, initialize an Express application and configure Multer:
const app = express();
// Set storage engine
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/'); // Specify the destination directory
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); // Specify the file name
}
});
// Initialize multer middleware
const upload = multer({ storage: storage });
In the above code, we've configured Multer to store uploaded files in the uploads/
directory. We've also specified a naming convention for the uploaded files.
Now, let's define a route to handle file uploads:
// Define a single file upload route
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully');
});
In this route, we've specified that we expect a single file with the field name file
. When a file is uploaded, Multer saves it to the specified destination directory.
Finally, start the server and listen on a port:
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
To test the file upload functionality, you can create a simple HTML form:
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
When you submit this form with a file selected, it will be uploaded to the server, and you'll receive a "File uploaded successfully" message.
app.js
// app.js
// Required modules
const express = require('express');
const multer = require('multer');
const path = require('path');
// Initialize Express app
const app = express();
// Set storage engine
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/'); // Specify the destination directory
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); // Specify the file name
}
});
// Initialize multer middleware
const upload = multer({ storage: storage });
// Define a single file upload route
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully');
});
// Serve the HTML form
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
index.html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h2>Upload a File</h2>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
</body>
</html>
To run this Code, you should have Node.js installed on your machine. Then, follow these steps:
app.js
file and copy the code provided above into it.uploads
directory in the project root (where app.js
is located).index.html
file and copy the HTML code provided above into it.npm init
to initialize a new Node.js project. Follow the prompts to create a package.json
file.npm install express multer
.node app.js
.http://localhost:3000
to access the file upload form.You should see a message saying "File uploaded successfully" after the file has been uploaded. The uploaded files will be stored in the uploads
directory.
Trending Posts
Create Input Floating Label in CSS and HTML...
CSS Card Hover Effects: Make Your Website Stand Ou...
Create a Rotate Image Gallery with HTML and CSS...
CSS Hover Effect | Web Development...
How to create MongoDB Free cloud Database - Atlas ...
Learn how to create CSS Button RGB Animation...
Create Responsive Sidebar with React JS and tailwi...
Build a JavaScript Carousel Slider With Example...
How to Disable the Submit Button in Formik...
How to Use Bootstrap 5 in Next.js...
codelearningpoint © 2024