Multer is an npm package commonly used in Node.js applications for handling multipart/form data, particularly for file uploads. It simplifies the process of handling file uploads by providing middleware that can be easily integrated into Express.js applications.
Prerequisites:Features of npm multer- File Uploads: Allows uploading files from client-side forms to the server.
- Middleware: Integrates seamlessly with Express.js middleware, making it easy to handle file uploads within routes.
- File Storage: Provides options for storing uploaded files on the server, such as in-memory storage, disk storage, or using a custom storage engine.
- File Filtering: Supports filtering uploaded files based on file type, size, and other criteria.
- Error Handling: Offers error handling for file uploads, including handling file size limits, invalid file types, and other upload-related errors.
Steps to Create Application and Installing PackageStep 1: Create a new folder for your project and navigate into it.mkdir multer-demo cd multer-demo Step 2: Initialize npm to create a package.json file.npm init -y Step 3: Install Express and Multer packages.npm install express multer Project Structure: Folder Structure Dependencies"dependencies": { "express": "^4.19.2", "multer": "^1.4.5-lts.1" } Example: In this example, we are using multer to handle file uploads in a Node.js server. The server code (server.js) sets up a multer storage configuration to store uploaded files in the “uploads” directory. The client-side HTML (index.html) contains a form for uploading files to the server, with the form’s action pointing to the upload route on the server.
HTML
<!--uploads/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>
<form action="http://localhost:3000/upload"
method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload File</button>
</form>
</body>
</html>
JavaScript
//server.js
const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage });
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Start the server by using the below command.
node server.js Open the index.html File.
Output:
|