{"id":2870,"date":"2022-07-21T08:56:55","date_gmt":"2022-07-21T13:56:55","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=2870"},"modified":"2022-07-21T08:56:59","modified_gmt":"2022-07-21T13:56:59","slug":"how-to-build-a-file-upload-rest-api-in-node-js-and-express","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/","title":{"rendered":"How to Build a File Upload Rest API in Node.js and Express?"},"content":{"rendered":"\n<p>Frameworks such as Express.js assist users in creating <a href=\"https:\/\/www.ibm.com\/cloud\/learn\/rest-apis\" target=\"_blank\" rel=\"noopener\">Restful APIs<\/a>. This article will be a tutorial on creating a Node.js REST API that uploads a file to a static folder on the server using Express and Multer. Also, you will work on getting a list of all the files&#8217; details, such as file name and URL, and downloading a file from the server with the link.<\/p>\n\n\n\n<p><strong>The following steps can be taken to build a file upload Rest API in Node.js using Express.js:<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>Add express, multer, and cors dependencies<\/strong><\/li><li><strong>Create a file upload Rest API project (optional)<\/strong><\/li><li><strong>Create a file upload middleware<\/strong><\/li><li><strong>Create a file upload controller<\/strong><\/li><li><strong>Define the file upload route<\/strong><\/li><li><strong>Run and test the file upload.<\/strong><\/li><\/ol>\n\n\n\n<p>Don&#8217;t worry if you feel a little lost with REST APIs. We&#8217;ve got you covered!<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#1_Add_Express_Multer_and_Cors_Dependencies\" >Add Express, Multer, and Cors Dependencies<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#2_Create_a_File_Upload_Rest_API_Project_Optional\" >Create a File Upload Rest API Project (Optional)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#3_Create_a_File_Upload_Middleware\" >Create a File Upload Middleware<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#Restrict_File_Size_With_Multer\" >Restrict File Size With Multer<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#4_Create_a_File_Upload_Controller\" >Create a File Upload Controller<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#Handle_Multer_File_Size_Limit_Error\" >Handle Multer File Size Limit Error<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#5_Define_the_File_Upload_Route\" >Define the File Upload Route<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#Create_the_Express_App_Server\" >Create the Express App Server<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#6_Run_and_Test_the_File_Upload\" >Run and Test the File Upload<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#Running_the_Server\" >Running the Server<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#What_is_Postman\" >What is Postman?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#Testing_With_Several_Requests\" >Testing With Several Requests<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#Add_File_Download_and_Fetch_Files_API_Endpoints_Optional\" >Add File Download and Fetch Files API Endpoints (Optional)&nbsp;<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#1_Create_File_Download_and_Fetch_Files_Controller\" >Create File Download and Fetch Files Controller<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#2_Create_the_File_Download_and_Fetch_Files_Routes\" >Create the File Download and Fetch Files Routes<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#3_Test_the_File_Download_and_Fetch_Files_API_Endpoint\" >Test the File Download and Fetch Files API Endpoint<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/#Wrapping_Up\" >Wrapping Up<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"1_Add_Express_Multer_and_Cors_Dependencies\"><\/span>1. Add Express, Multer, and Cors Dependencies<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Before moving on with making our REST API, certain requirements must be met. First, you must have some knowledge of programming fundamentals in <a href=\"https:\/\/www.becomebetterprogrammer.com\/javascript-hard-to-understand\/\">JavaScript<\/a> and Node.js but, more importantly, a lot of zeal to become a better programmer and learn something new. So keep reading to learn more!<\/p>\n\n\n\n<p>To create this REST API, you will have to install the following on your system:<\/p>\n\n\n\n<p>express 4.17.1<br>multer 1.4.2<br>cors 2.8.5<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"2_Create_a_File_Upload_Rest_API_Project_Optional\"><\/span>2. Create a File Upload Rest API Project (Optional)<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Node.js is a run-time environment that comes with everything you need to run a JavaScript program. Before content is sent to a web browser, it is used to run scripts on the server to render it. You will learn <a href=\"https:\/\/www.becomebetterprogrammer.com\/how-to-set-up-basic-node-js-express-js-server-with-typescript\/\">how to set up basic Node.js server<\/a> in this guide.<\/p>\n\n\n\n<p>The Node Package Manager, or NPM for short, is a repository and application for creating and exchanging JavaScript code.<\/p>\n\n\n\n<p>Therefore, you must have both, <code>Node.js<\/code> and <code>npm<\/code> ,&nbsp; set up on your system.<\/p>\n\n\n\n<p>Once that is finished, open your system&#8217;s command prompt and change the current directory to the project&#8217;s root folder.<\/p>\n\n\n\n<p>Then use the npm command below to install the Express, Multer, and CORS modules:<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>npm install express multer cors<\/code><\/pre>\n\n\n\n<p>After it successfully runs, the <code><strong>package<\/strong>.<strong>json<\/strong><\/code> file in your project directory will look something like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{\n  \"name\": \"node-js-express-upload-download-files\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Node.js Express Rest API for Uploading Files\",\n  \"main\": \"server.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" &amp;&amp; exit 1\"\n  },\n  \"keywords\": &#91;\n    \"node js\",\n    \"upload\",\n    \"download\",\n    \"file\",\n    \"multipart\",\n    \"rest api\",\n    \"express\"\n  ],\n  \"author\": \"unknown\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"cors\": \"^2.8.5\",\n    \"express\": \"^4.17.1\",\n    \"multer\": \"^1.4.2\"\n  }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"3_Create_a_File_Upload_Middleware\"><\/span>3. Create a File Upload Middleware<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The middleware will use <a href=\"https:\/\/www.npmjs.com\/package\/multer\" target=\"_blank\" rel=\"noopener\">Multer<\/a> to manage multipart\/form-data and upload files.<\/p>\n\n\n\n<p>Create a file called <code>upload.js<\/code> inside the middleware folder of your project directory and fill it with the information listed below:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ import the multer module before configuring it to use the disc storage engine\nconst util = require(\"util\");\nconst multer = require(\"multer\");\nconst maxSize = 2 * 1024 * 1024;\nlet storage = multer.diskStorage({\n&nbsp; destination: (req, file, cb) =&gt; {\n&nbsp; &nbsp; cb(null, __basedir + \"\/resources\/static\/assets\/uploads\/\");\n&nbsp; },\n&nbsp; filename: (req, file, cb) =&gt; {\n&nbsp; &nbsp; console.log(file.originalname);\n&nbsp; &nbsp; cb(null, file.originalname);\n&nbsp; },\n});\n\nlet uploadFile = multer({\n&nbsp; storage: storage,\n&nbsp; limits: { fileSize: maxSize },\n}).single(\"file\");\n\n\/\/ create the exported middleware object\nlet uploadFileMiddleware = util.promisify(uploadFile);\nmodule.exports = uploadFileMiddleware;<\/code><\/pre>\n\n\n\n<p>The code in the previous block imports the multer module before configuring it to use the disc storage engine. For this, we employ the function <code>multer.diskStorage()<\/code>, which has two properties:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>destination: The folder used to store the uploaded files or the path where the images will be stored. We&#8217;ll make it &#8220;.\/uploads.&#8221;<\/li><li>filename: chooses the name that will be saved in storage or the file&#8217;s name that will be placed in the desired folder. Simply using its original name will suffice.<\/li><\/ol>\n\n\n\n<p>Lastly, <code>util.promisify()<\/code> creates the exported middleware object that can later be used with <code><strong>async<\/strong>-<strong>await<\/strong><\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Restrict_File_Size_With_Multer\"><\/span>Restrict File Size With Multer<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>With the new multer API, users can limit the size of files by adding limits: <code>{ fileSize: maxSize }<\/code>&nbsp; to the object passed to <code>multer()<\/code>. Our file size will be limited to 2 MB. Let&#8217;s examine this in practice.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let storage = multer.diskStorage(...);\nconst maxSize = 2 * 1024 * 1024; \/\/ 2 MB\nlet uploadFile = multer({\n  storage: storage,  \/\/ adding limits\n  limits: { fileSize: maxSize }\n}).single(\"file\");<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"4_Create_a_File_Upload_Controller\"><\/span>4. Create a File Upload Controller<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>To create a controller for our REST API, first, navigate to the controller folder and create file.controller.js:<\/p>\n\n\n\n<p>To define the File Upload method, we export <code>upload()<\/code> function that will do the following:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>It will use a middleware function to upload a file.<\/li><li>Next, it will catch Multer errors inside the middleware function.<\/li><li>Finally, return <code>response<\/code> with <code>message<\/code>.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const uploadFile = require(\"..\/middleware\/upload\");\nconst upload = async (req, res) =&gt; {\n  try {\n    await uploadFile(req, res);\n    if (req.file == undefined) {\n      return res.status(400).send({ message: \"Upload a file please!\" });\n    }    \n    res.status(200).send({\n      message: \"The following file was uploaded successfully: \" + req.file.originalname,\n    });\n  } catch (err) { \\\\ error handling\n    res.status(500).send({\n      message: `Unable to upload the file: ${req.file.originalname}. ${err}`,\n    });\n  }\n};\n\nmodule.exports = upload;<\/code><\/pre>\n\n\n\n<p>Let&#8217;s review the key components of this code. We start by calling the middleware function <code>uploadFile()<\/code>. Then, send the 400 status code in the response if the HTTP request doesn&#8217;t contain any files. Then, the error is also caught, and a 500 status is sent with an error message.<\/p>\n\n\n\n<p>Once that is resolved, we need to write some code to handle instances when users try to upload files larger than the allowed size.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Handle_Multer_File_Size_Limit_Error\"><\/span>Handle Multer File Size Limit Error<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Moreover, the error can be handled by checking the error code <code>(LIMIT_FILE_SIZE)<\/code> in the <code><strong>catch<\/strong>()<\/code> block:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const upload = async (req, res) =&gt; {&nbsp;&nbsp;\/\/ try to upload\n&nbsp; try {\n&nbsp; &nbsp; await uploadFile(req, res);\n&nbsp; &nbsp; ...\n&nbsp; } catch (err) {&nbsp;&nbsp;&nbsp;&nbsp;\/\/ error handling\n&nbsp; &nbsp; if (err.code == \"LIMIT_FILE_SIZE\") {\n&nbsp; &nbsp; &nbsp; return res.status(500).send({\n&nbsp; &nbsp; &nbsp; &nbsp; message: \"File larger than 2MB cannot be uploaded!\",\n&nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; }\n&nbsp; &nbsp; res.status(500).send({\n&nbsp; &nbsp; &nbsp; message: `Unable to upload the file: ${req.file.originalname}. ${err}`,\n&nbsp; &nbsp; });\n&nbsp; }\n};<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"5_Define_the_File_Upload_Route\"><\/span>5. Define the File Upload Route<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Whenever the server receives an HTTP request from a client, we need to determine how the server should respond by setting up the route:<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>POST \/upload: upload()<\/code><\/pre>\n\n\n\n<p>So we need to create an <code>index.js<\/code> file inside the routes folder that will contain the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const express = require(\"express\");\nconst router = express.Router();\nconst controller = require(\"..\/controller\/file.controller\");\nlet routes = (app) =&gt; {\n  router.post(\"\/upload\", controller.upload);\n  app.use(router);\n};\nmodule.exports = routes;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_the_Express_App_Server\"><\/span>Create the Express App Server<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Finally, we can create an Express server in server.js:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ import modulesconst cors = require(\"cors\");\nconst express = require(\"express\");\n\n\/\/ create REST apiconst app = express();\nglobal.__basedir = __dirname;\nvar corsOptions = {\n  origin: \"http:\/\/localhost:8080\"\n};\napp.use(cors(corsOptions));\nconst initRoutes = require(\".\/src\/routes\");\napp.use(express.urlencoded({ extended: true }));\ninitRoutes(app);\/\/ port where server will run\nlet port = 8080;\napp.listen(port, () =&gt; {\n  console.log(`Running at localhost:${port}`);\n});<\/code><\/pre>\n\n\n\n<p>The express and cors modules are first imported by the code above. Express is used to create the REST API, and cors offers Express middleware with several options to enable CORS. The code then creates an Express app to add cors middlewares the <code>app.use()<\/code> method. Take note of the default setting, which instructs the server to listen on port 8080 for incoming requests.<\/p>\n\n\n\n<p>So, after all this coding, your project directory should contain the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><em>resources\/static\/assets\/uploads<\/em>: The folder for storing uploaded files.<\/li><li><em>middleware\/upload.js<\/em>: This initializes the Multer Storage engine and defines the middleware function to save uploaded files in the uploads folder.<\/li><li><em>file.controller.js exports Rest APIs<\/em>: With the controller, you can POST a file, GET all files&#8217; information, or download a file with a URL.<\/li><li><em>routes\/index.js<\/em>: This defines routes for endpoints that are called from HTTP Client and uses a controller to handle requests.<\/li><li><em>server.js<\/em>: initializes routes and runs the Express app.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"6_Run_and_Test_the_File_Upload\"><\/span>6. Run and Test the File Upload<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Running_the_Server\"><\/span>Running the Server<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Before moving on, the uploads folder must first be created with the path resources\/static\/assets.<\/p>\n\n\n\n<p>The server will then be started by running the following command in the project root directory:<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>node server.js.<\/code><\/pre>\n\n\n\n<p>You should receive a notification that the server is starting up and listening on the designated port, in this case, 8080.<\/p>\n\n\n\n<p>Let&#8217;s now make an HTTP POST request with a file using Postman on the client-side.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_Postman\"><\/span>What is Postman?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p><a href=\"https:\/\/www.postman.com\/\" target=\"_blank\" rel=\"noopener\">Postman<\/a> is perhaps the most popular API testing tool on the market. It is an HTTP client that examines HTTP requests using a graphical user interface, allowing us to get various responses that must then be verified. To help you create better APIs faster, Postman streamlines collaboration and simplifies every stage of the API lifecycle.<\/p>\n\n\n\n<p>Postman has numerous endpoint interactions. Here are some of them:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>GET: Obtain information&nbsp;<\/li><li>POST: Add information<\/li><li>PUT: Replace information<\/li><li>PATCH: Update certain information<\/li><li>DELETE: Delete information<\/li><\/ul>\n\n\n\n<p class=\"has-light-green-cyan-background-color has-background\"><strong>Tip<\/strong>: For a smoother experience and to quickly get started using the Postman API Platform, download the Postman desktop application. Additionally, you must download the Postman desktop agent if you use the Postman web client. The Postman agent enables API request sending from your browser version of Postman by getting around browsers&#8217; Cross Object Resource Sharing (CORS) restrictions. So another good program to install for convenience is Postman Agent.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Testing_With_Several_Requests\"><\/span>Testing With Several Requests<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>To test this, open Postman, choose the POST option, and then enter http:\/\/localhost:8080\/upload next to it. Next, select the file you want, such as user.doc, and click &#8220;Send&#8221; to send the request. You can anticipate a response along these lines:<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{\nmessage: \"The following file was uploaded successfully: user.doc\"\n}<\/code><\/pre>\n\n\n\n<p>After uploading the files, you should check the uploads folder to see if those files are there.<\/p>\n\n\n\n<p>Now, if you try and upload a file larger than the maximum file size, you will receive the following response:<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{\nmessage: \"File larger than 2MB cannot be uploaded!\"\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Add_File_Download_and_Fetch_Files_API_Endpoints_Optional\"><\/span>Add File Download and Fetch Files API Endpoints (Optional)&nbsp;<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"1_Create_File_Download_and_Fetch_Files_Controller\"><\/span>1. Create File Download and Fetch Files Controller<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Like we did above for the File Upload method, we define two functions for file information and download:<\/p>\n\n\n\n<p><code>getListFiles()<\/code>: This function returns a list of all files, and their URL, in the uploads folder.<\/p>\n\n\n\n<p><code>download()<\/code>: This function receives a file name as input parameter. Then, it uses the Express <code>res.download<\/code> method to transfer the file as an &#8216;attachment&#8217; to a path (directory + filename).<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const getListFiles = (req, res) =&gt; {\n  const directoryPath = __basedir + \"\/resources\/static\/assets\/uploads\/\";\n  fs.readdir(directoryPath, function (err, files) {\n    if (err) {\n      res.status(500).send({\n        message: \"There was an issue in scanning the files!\",\n      });\n    }\n    let fileInfos = &#91;];\n    files.forEach((file) =&gt; {\n      fileInfos.push({\n        name: file,\n        url: baseUrl + file,\n      });\n    });\n    res.status(200).send(fileInfos);\n  });\n};\n\nconst download = (req, res) =&gt; {\n  const fileName = req.params.name;  \/\/ define uploads folder path\n  const directoryPath = __basedir + \"\/resources\/static\/assets\/uploads\/\";\n  res.download(directoryPath + fileName, fileName, (err) =&gt; {\n    if (err) {\n      res.status(500).send({\n        message: \"There was an issue in downloading the file. \" + err,\n      });\n    }\n  });\n};\n\nmodule.exports = {\n  getListFiles,\n  download,\n};<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"2_Create_the_File_Download_and_Fetch_Files_Routes\"><\/span>2. Create the File Download and Fetch Files Routes<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>We can have two routes and an associated controller for file listing and downloading:&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code langauge-bash\"><code>GET \/files\/&#91;fileName]: download()\nGET \/files: getListFiles()<\/code><\/pre>\n\n\n\n<p>So we can update the index.js file inside routes folder that will contain the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const express = require(\"express\");\nconst router = express.Router();\nconst controller = require(\"..\/controller\/file.controller\");\nlet routes = (app) =&gt; {\n  router.post(\"\/upload\", controller.upload);\n  router.get(\"\/files\", controller.getListFiles);\n  router.get(\"\/files\/:name\", controller.download);\n  app.use(router);\n};\nmodule.exports = routes;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"3_Test_the_File_Download_and_Fetch_Files_API_Endpoint\"><\/span>3. Test the File Download and Fetch Files API Endpoint<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>As you did with file upload, you can get all the information about the files you&#8217;ve uploaded by sending a GET request to http:\/\/localhost:8080\/file. Once again, it will be easiest if you use Postman.<\/p>\n\n\n\n<p>You can also download any file from one of the paths provided in response to the request\u2014for example, http:\/\/localhost:8080\/files\/user.doc.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Wrapping_Up\"><\/span>Wrapping Up<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Congratulations! In this post, you learned how to build a Node.js Express Rest API that uploads files into a static folder. In this project, you created a middleware that handles a multipart file using Multer. Also, you learned how to restrict file uploads based on a file size limit and properly handle size limit errors. You have also learned how to use Postman to test your API servers.<\/p>\n\n\n\n<p><strong>Was this article helpful?<\/strong><\/p>\n\n\n\n<p>Please, let us know your opinions by replying on <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noopener\">Twitter to become a better programmer.<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Frameworks such as Express.js assist users in creating Restful APIs. This article will be a tutorial on creating a Node.js REST API that uploads a file to a static folder on the server using Express and Multer. Also, you will work on getting a list of all the files&#8217; details, such as file name and &#8230; <a title=\"How to Build a File Upload Rest API in Node.js and Express?\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/how-to-build-a-file-upload-rest-api-in-node-js-and-express\/\" aria-label=\"More on How to Build a File Upload Rest API in Node.js and Express?\">Read more<\/a><\/p>\n","protected":false},"author":6,"featured_media":3251,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[23,16],"tags":[],"class_list":["post-2870","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-node-js","category-javascript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2870","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=2870"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2870\/revisions"}],"predecessor-version":[{"id":3254,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2870\/revisions\/3254"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/3251"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=2870"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=2870"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=2870"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}