How to Handle file upload in Node with Multer and Postman
Last Updated :
26 Jul, 2024
In this article, we will discuss about file upload functionality using Node, Multer and Postman. File Uploading is a significant functionality of any web service to get the data from the users in the form of files.
To implement this feature we will use Node JS with Express and Multer library. Finally, we will use the Postman API platform to test the REST endpoint for file uploading.
Prerequisites
The following tools should be installed in your system to follow along with this article, incase you don't have it already installed use the given links (node, postman) to download and install it in your system. Make sure you are using the same version of the tools mentioned.
Approach to handle file upload in Node
Let's discuss our approach for implementing the file upload functionality in Node.js.
- Create a basic node application using the node package manager.
- Add the express.js and multer dependency to the project.
- Create a `/upload` endpoint in the api and use the post method to accept file inputs.
- Create a multer instance by importing the multer library and configure the storage location, file size limit, file type, etc.
- Pass the multer instance to the `upload` route as a middleware to parse every request before sending the response.
- Run the server and test the REST endpoint using the Postman API tool.
- Open your Postman tool and enter your localhost URL.
- To send the files set the body type as `form-data` and attach the file.
- Hit the send button to upload the file from postman to the node.js api and finally verify whether the files have been saved in the backend.
Project Structure:
project structureHandling File Upload in Node JS
Follow the step by step procedure to handle file upload in node, create a folder to store the project files and open that folder in VS Code or any of your preferred Text Editor. The entire workflow has been divided into three major process,
- Create a basic express application with Node.js
- Set up the file upload REST endpoint and configure the multer library to save the files to the disk.
- Test the file upload REST endpoint using the Postman API tool.
Steps to create Basic Express Application
Step 1: Create a basic node application with the below npm command.
npm init -y
`-y` flag is used to say yes to all of the details asked by npm, if you need to change any option, answer it manually by omitting the flag in the command.
init node appStep 2:
- Install the express.js and multer dependency using the npm install command.
- The dependencies will be installed under a folder called node_modules under the current directory.
npm install --save express multer
installing dependencies- --save option is used to add these libraries in the package.json file as a dependency for running the application.
Step 3: Create a file named server.js under the same directory to host the express server. Add the below code to bootstrap the server for giving a hello message on hitting the "/" endpoint
JavaScript
const express = require("express");
const app = express();
// port for our project to run
const PORT = 8080;
// A simple greeting message to
// test the app
app.get("/", (req, res) => {
res.send("Hello from Express!");
});
// Start the server using listen method of express
// pass the port and callback function on successful start
app.listen(8080, () => {
console.log(`server is started and
listening at port: ${PORT}`);
});
A simple get method is added to the "/" path to check whether the app is starting fine and responding back to the request.
Step 4: Start the server and test the initial greeting message in Postman, to start the server use the below command.
npm start
Step 5:
- Once the server is started, open Postman and create a new HTTP request using the `New` button located after My Workspace in the screen.
- Enter your server url in the address bar of the request and select the HTTP method for the request, here => http://localhost:8080/ and GET method.
- Click the send button to send the request to the server.
initial hello ouput- Once the request has been sent, the server will respond with plain text saying "Hello from Express!".
- You can find the response from the server in the below area of the request under the Body tab.
Adding File Upload functionality with Multer
Step 6: Create a file named file-upload.js in the current directory to store the file upload handling functions and Multer configuration.
JavaScript
const multer = require("multer");
const path = require("node:path");
const storageConfig = multer.diskStorage({
// destinations is uploads folder
// under the project directory
destination: path.join(__dirname, "uploads"),
filename: (req, file, res) => {
// file name is prepended with current time
// in milliseconds to handle duplicate file names
res(null, Date.now() + "-" + file.originalname);
},
});
// file filter for filtering only images
const fileFilterConfig = function(req, file, cb) {
if (file.mimetype === "image/jpeg"
|| file.mimetype === "image/png") {
// calling callback with true
// as mimetype of file is image
cb(null, true);
} else {
// false to indicate not to store the file
cb(null, false);
}
};
// creating multer object for storing
// with configuration
const upload = multer({
// applying storage and file filter
storage: storageConfig,
limits: {
// limits file size to 5 MB
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilterConfig,
});
module.exports = upload;
Explanation of the above code:
- A multer object is created as "upload" and exported from the module, in the multer object storage, limits, fileFilter options are used to configure the multer object.
- Storage option is for configuring the process of storing the file, like the destination folder, file name to use for the uploaded files.
- destination: uploads, a folder is created inside the project directory to store the uploaded files.
- filename: Current time in milliseconds is fetched with Date.now() and prepended to avoid conflict of file names.
- FileFilter option is used to filter out files, call the cb() with true to pass the file, here we are filtering out files which are not images.
Step 7: Import the upload function in the server.js to use in the "/upload" REST endpoint.
JavaScript
const express = require("express");
const app = express();
// port for our project to run
const PORT = 8080;
// A simple greeting message to
// test the app
app.get("/", (req, res) => {
res.send("Hello from Express!");
});
// add code for upload functinality using POST method
app.post("/upload", upload.single("file"), (req, res) => {
// check whether req.file contians the file
// if not multer is failed to parse so notify the client
if (!req.file) {
res.status(413).send(`File not uploaded!, Please
attach jpeg file under 5 MB`);
return;
}
// successfull completion
res.status(201).send("Files uploaded successfully");
});
// Start the server using listen method of express
// pass the port and callback function on successful start
app.listen(8080, () => {
console.log(`server is started and
listening at port: ${PORT}`);
});
Explanation of the above code:
- Here we have created a post request and passed the upload object's single function as a middleware to handle the file storing.
- upload.single("file") is used to accept a single file input and store it under the destination folder, where "file" is the name of the FORM-DATA attachment, this should match when we send the request.
- Once, multer has handled the request, the file will be stored under req.file. For simple error handling we will check the req.file, if it is undefined we will intimate the client about this client error with a error message.
Testing File Upload with Postman
Step 8:
- Start the server and enter the "http://localhost:8080/upload" endpoint and use the POST method.
- Add the file under BODY tab, use the "FORM-DATA" encoding for the body and send the request.
Output:
Similar Reads
How to handle file upload in Node.js ?
File upload can easily be done by using Formidable. Formidable is a module that we can install on our project directory by typing the command npm install formidableApproach: We have to set up a server using the HTTPS module, make a form that is used to upload files, save the uploaded file into a tem
3 min read
How to Upload File and JSON Data in Postman?
Postman is a very famous API development tool used to test APIs. Postman simplifies the process of the API lifecycle to create and test better APIs. Now, while we are working with APIs sometimes we need to send JSON as data or upload a file through API. There may be a scenario where we have to do bo
4 min read
How to Upload File using formidable module in Node.js ?
A formidable module is used for parsing form data, especially file uploads. It is easy to use and integrate into your project for handling incoming form data and file uploads. ApproachTo upload file using the formidable module in node we will first install formidable. Then create an HTTP server to a
2 min read
How to Upload File with Progress Bar using Node.js ?
Uploading files in NodeJS involves transferring files from the client's location to the server's location. A progress bar is a visual component that displays the percentage of the total file upload. In this tutorial, we will create a local server and demonstrate how to upload files to a destination
4 min read
Upload Files to Local public folder in NodeJs using Multer
Uploading files to a local public folder in Node.js using Multer involves a few steps. This article helps you set it up. Install Multer First, you need to install Multer, which is a Node.js middleware for handling multipart/form-data, primarily used for uploading files. npm install multerSet Up Your
3 min read
How to read and write files in Node JS ?
NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
2 min read
How to test API Endpoints with Postman and Express ?
Postman, a popular API development and testing tool allowing developers to interact with APIs. In this guide, we'll explore the basics of testing API endpoints using Postman and Express, providing clear steps and examples. Prerequisites:Basics of Express JS and Node JS.Postman should be installed.St
2 min read
How to implement a simple file upload with multipart form in Angular ?
In this article, we will see how to implement a simple file upload functionality in an Angular application. File uploading is a most common and significant functionality of any web application, to get the data in terms of files from the user or client to the server. We will see how to implement the
7 min read
React Single File Upload with Multer and Express.js
When we want to add functionality for uploading or deleting files, file storage becomes crucial, whether it's for website or personal use. The File Storage project using Express aims to develop a web application that provides users with a secure and efficient way to store and manage their files onli
5 min read
How to read and write JSON file using Node ?
Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and
3 min read