Handling file inputs in expressjs application using multer
Handling file uploads in a web application is a common task. Whether you're building a profile picture upload feature, document storage, or handling media files, understanding how to handle file uploads securely and efficiently is crucial. In this guide, we'll see how to handle file uploads using expressjs and multer.
What is multer?
Multer is a middleware for handling multipart/form-data, primarily used for uploading files in Node.js applications. It supports file parsing, storage management, and file validation, allowing users to save files to local storage or cloud storage. Multer is commonly used with Express.js to handle file uploads efficiently.
Prerequisites
Node.js and npm (Node Package Manager)
Step 1. Setup the basic nodejs project using the commands below one by one.
npm init -y
npm install express multer
npm init -y - initializes the node project by creating a package.json file
npm install express multer - installs the required express (to create server) and multer (to handle file) dependencies.
Step 2. Create a simple express application
Create a file index.js, inside the file paste the below code to create a simple express server
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
You can test the above app by running command node index.js in the terminal and visiting localhost:3000 in the browser.
Step 3. Setup multer to handle file related operations
const express = require('express');
const multer = require('multer'); // add this line
const path = require('path'); // add this line
const app = express();
const port = 3000;
// add the below code to set up multer storage to store the file in desired location
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // save files in the "uploads" folder in cwd
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname)); // give the file a unique name
},
});
//// OPTIONAL
// If you do not want to store the file in local machine storage and instead wants to save it any cloud storage service etc. you can set the storage as follows:
const storage = multer.memoryStorage(); //
// Initialize multer with the storage configuration
const upload = multer({ storage });
// Endpoint to handle single file upload
app.post('/upload', upload.single('file'), fileHandler); // we will create fileHandler in next step
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step 4. Handle the file coming from request body using fileHandler function
function fileHandler(req, res){
const file = req.file;
// if no file found in request body
if (!file) {
return res.status(400).send('No file uploaded.');
}
// if you just want to upload file to the local machine, you can return from here
return res.status(400).send('Files uploaded successfully');
//However if you want to perform some addition tasks, like uploading file to cloud storage, you can do as follows:
//Create a file blob
const fileBuffer = Buffer.from(file.buffer);
const fileBlob = new Blob([fileBuffer]);
//logic to upload the fileblob on the cloud
return res.status(400).send('Files uploaded to cloud successfully');
}
Hence, using the above steps you can handle files in an express js application