{"id":1890,"date":"2019-03-12T10:47:37","date_gmt":"2019-03-12T05:17:37","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=1890"},"modified":"2023-12-22T19:05:59","modified_gmt":"2023-12-22T13:35:59","slug":"multiple-file-upload-node-js","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/multiple-file-upload-node-js\/","title":{"rendered":"How to Upload Multiple Files Using Node.js"},"content":{"rendered":"<p>We use Node.js to build web application backend and one of the use cases that comes often is a file upload feature. In this tutorial, we are going to learn and build an application that can let user upload multiple files using Node.js.<\/p>\n<p><center><a class=\"button-rounded button-flat-caution\" href=\"https:\/\/youtu.be\/0PYSlOutMNw\" title=\"Demo of multiple file upload using Nodejs\" target=\"_blank\" rel=\"noopener noreferrer\"><i class=\"fa fa-code\"><\/i>LIVE DEMO<\/a> <a class=\"button-rounded button-flat\" href=\"https:\/\/codeload.github.com\/codeforgeek\/multiple-file-upload-node\/zip\/master\" target=\"_blank\" rel=\"noopener noreferrer\"><i class=\"fa fa-github\"><\/i>DOWNLOAD<\/a><\/center><\/p>\n<h2>Our application : <\/h2>\n<p>I am going to develop same application as I have done in <a href=\"https:\/\/codeforgeek.com\/ajax-file-upload-node-js\/\" target=\"_blank\" rel=\"noopener noreferrer\">last<\/a> tutorial with some additional code changes which makes it multiple file upload.<\/p>\n<p>We are going to use basic FORM submit along with <strong>Ajax submit<\/strong> jQuery plugin to make it asynchronous. Here is our package.json file.<\/p>\n<div class=\"file_name\">package.json<\/div>\n<p><code lang='javascript'><br \/>\n{<br \/>\n  \"name\": \"file_upload\",<br \/>\n  \"version\": \"0.0.1\",<br \/>\n  \"dependencies\": {<br \/>\n    \"body-parser\": \"^1.14.2\",<br \/>\n    \"express\": \"4.13.3\",<br \/>\n    \"multer\": \"1.1.0\"<br \/>\n  },<br \/>\n  \"devDependencies\": {<br \/>\n    \"should\": \"~7.1.0\",<br \/>\n    \"mocha\": \"~2.3.3\",<br \/>\n    \"supertest\": \"~1.1.0\"<br \/>\n  }<br \/>\n}<br \/>\n<\/code><br \/>\nRun following command to install the dependencies.<br \/>\n<code>npm install<\/code><\/p>\n<p>Here is our Server file with multiple file upload support.<\/p>\n<div class=\"file_name\">Server.js<\/div>\n<p><code lang='javascript'><br \/>\nvar express = require(\"express\");<br \/>\nvar bodyParser = require(\"body-parser\");<br \/>\nvar multer = require('multer');<br \/>\nvar app\t= express();<\/p>\n<p>app.use(bodyParser.json());<\/p>\n<p>var storage = multer.diskStorage({<br \/>\n  destination: function (req, file, callback) {<br \/>\n    callback(null, '.\/uploads');<br \/>\n  },<br \/>\n  filename: function (req, file, callback) {<br \/>\n    callback(null, file.fieldname + '-' + Date.now());<br \/>\n  }<br \/>\n});<\/p>\n<p>var upload = multer({ storage : storage }).array('userPhoto',2);<\/p>\n<p>app.get('\/',function(req,res){<br \/>\n      res.sendFile(__dirname + \"\/index.html\");<br \/>\n});<\/p>\n<p>app.post('\/api\/photo',function(req,res){<br \/>\n\tupload(req,res,function(err) {<br \/>\n\t\t\/\/console.log(req.body);<br \/>\n\t\t\/\/console.log(req.files);<br \/>\n\t\tif(err) {<br \/>\n\t\t\treturn res.end(\"Error uploading file.\");<br \/>\n\t\t}<br \/>\n\t\tres.end(\"File is uploaded\");<br \/>\n\t});<br \/>\n});<\/p>\n<p>app.listen(3000,function(){<br \/>\n    console.log(\"Working on port 3000\");<br \/>\n});<br \/>\n<\/code><\/p>\n<p>The only line you need to put your focus on is this<br \/>\n<code lang='javascript'><br \/>\nvar upload = multer({ storage : storage }).array('userPhoto',2);<br \/>\n<\/code><br \/>\nHere rather than <strong>.single()<\/strong> we are using <strong>.array(selector,fileLimit)<\/strong> of Multer. Multer will accept array of files limiting to max 2 file at each time. You can of course increase the number as you may need. Rest of the code is same as previous tutorial.<\/p>\n<p>Here is our HTML file.<\/p>\n<div class=\"file_name\">Index.html<\/div>\n<p><code lang='javascript'><br \/>\n<html><br \/>\n  <head><br \/>\n    <title>File upload Node.<\/title><br \/>\n  <\/head><br \/>\n  <body><\/p>\n<form id=\"uploadForm\"\n          enctype=\"multipart\/form-data\"\n          action=\"\/api\/photo\"\n          method=\"post\"><br \/>\n      <input type=\"file\" name=\"userPhoto\" multiple \/><br \/>\n      <input type=\"submit\" value=\"Upload Image\" name=\"submit\"><br \/>\n      <input type='text' id='random' name='random'><br \/>\n      <span id = \"status\"><\/span><br \/>\n    <\/form>\n<p>  <\/body><br \/>\n<\/html><br \/>\n<\/code><\/p>\n<p>Here is our JavaScript code which we place in same HTML file. You can place it in different file. Put this code below closing tag of BODY.<\/p>\n<div class='file_name'>index.html<\/div>\n<p><code lang='javascript'><br \/>\n  <script src=\"http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.7.1\/jquery.min.js\"><\/script><br \/>\n  <script src=\"http:\/\/cdnjs.cloudflare.com\/ajax\/libs\/jquery.form\/3.51\/jquery.form.min.js\"><\/script><br \/>\n  <script>\n  $(document).ready(function() {\n     $('#uploadForm').submit(function() {\n        $(\"#status\").empty().text(\"File is uploading...\");\n        $(this).ajaxSubmit({\n            error: function(xhr) {\n\t      status('Error: ' + xhr.status);\n            },\n            success: function(response) {\n\t\tconsole.log(response)\n\t        $(\"#status\").empty().text(response);\n            }\n\t});\n\treturn false;\n    });    \n});\n<\/script><br \/>\n<\/code><br \/>\nOn Form submit, we will stop the page refresh by returning FALSE and call the API using ajaxSubmit(). You can Add this code in separate file and add it below the jquery.form or copy and paste just below this line.<br \/>\n<code><br \/>\n<script src=\"http:\/\/cdnjs.cloudflare.com\/ajax\/libs\/jquery.form\/3.51\/jquery.form.min.js\"><\/script><\/p>\n<p><script>\n------Paste above code ------\n<\/script><br \/>\n<\/code><\/p>\n<h2>Running the application<\/h2>\n<p>To run the application, switch to project directory and type following command.<br \/>\n<code>node Server.js<\/code><br \/>\n<img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/running-the-app.png\" alt=\"Running file upload app\" width=\"1102\" height=\"536\" class=\"alignnone size-full wp-image-1894\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/running-the-app.png 1102w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/running-the-app-300x146.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/running-the-app-768x374.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/running-the-app-1024x498.png 1024w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/running-the-app-640x311.png 640w\" sizes=\"(max-width: 1102px) 100vw, 1102px\" \/><\/p>\n<p>Visit <strong>localhost:3000<\/strong> to view the app. Choose multiple files from the selection window and see the console.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/select-multiple-file.png\" alt=\"Selecting multiple files for app\" width=\"1535\" height=\"876\" class=\"alignnone size-full wp-image-1896\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/select-multiple-file.png 1535w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/select-multiple-file-300x171.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/select-multiple-file-768x438.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/select-multiple-file-1024x584.png 1024w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/select-multiple-file-640x365.png 640w\" sizes=\"(max-width: 1535px) 100vw, 1535px\" \/><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/upload-multiple-file.png\" alt=\"Upload done\" width=\"1175\" height=\"674\" class=\"alignnone size-full wp-image-1895\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/upload-multiple-file.png 1175w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/upload-multiple-file-300x172.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/upload-multiple-file-768x441.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/upload-multiple-file-1024x587.png 1024w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/01\/upload-multiple-file-640x367.png 640w\" sizes=\"(max-width: 1175px) 100vw, 1175px\" \/><\/p>\n<h2>Further enhancement<\/h2>\n<p>If you want to have different control for file rather than single HTML control then you need to define multiple files control in HTML with same <strong>name<\/strong> in order to recognize the Multer that it is array of files. Here is how you can do this. Currently we are using this.<br \/>\n<code lang='html'><br \/>\n<input type=\"file\" name=\"userPhoto\" multiple\/><br \/>\n<\/code><br \/>\nYou can write same like this.<br \/>\n<code lang='html'><br \/>\n<input type=\"file\" name=\"userPhoto\"\/><br \/>\n<input type=\"file\" name=\"userPhoto\"\/><br \/>\n<\/code><br \/>\nThere is no change in back-end code required for above change.<\/p>\n<h2>Further Study<\/h2>\n<p><a href=\"https:\/\/codeforgeek.com\/file-uploads-using-node-js\/\" rel=\"noopener noreferrer\" target=\"_blank\">File uploads using Node.js<\/a><br \/>\n<a href=\"https:\/\/codeforgeek.com\/ajax-file-upload-node-js\/\" rel=\"noopener noreferrer\" target=\"_blank\">Ajax file upload in Node.js<\/a><br \/>\n<a href=\"https:\/\/codeforgeek.com\/nodejs-mysql-tutorial\/\" rel=\"noopener noreferrer\" target=\"_blank\">Node.js MySQL Tutorial<\/a><br \/>\n<a href=\"https:\/\/codeforgeek.com\/real-time-notification-system-using-socket-io\/\" rel=\"noopener noreferrer\" target=\"_blank\">HTML5 Push Notification System Using Nodejs MySQL Socket.io<\/a><\/p>\n<h2>Conclusion<\/h2>\n<p>Multer is one of the easy node modules you can use with Express for file upload. It allows you to add various validation and support single as well as multiple file uploads. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>We use Node.js to build web application backend and one of the use cases that comes often is a file upload feature. In this tutorial, we are going to learn and build an application that can let user upload multiple files using Node.js. LIVE DEMO DOWNLOAD Our application : I am going to develop same [&hellip;]<\/p>\n","protected":false},"author":69,"featured_media":5866,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[22,14,18],"tags":[],"class_list":["post-1890","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-express","category-nodejs","category-tutorial"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/03\/how-to-upload-multiple-files-using-nodejs.jpg",1500,750,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/03\/how-to-upload-multiple-files-using-nodejs-150x150.jpg",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/03\/how-to-upload-multiple-files-using-nodejs-300x150.jpg",300,150,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/03\/how-to-upload-multiple-files-using-nodejs-768x384.jpg",768,384,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/03\/how-to-upload-multiple-files-using-nodejs-1024x512.jpg",1024,512,true],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/03\/how-to-upload-multiple-files-using-nodejs.jpg",1500,750,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/03\/how-to-upload-multiple-files-using-nodejs.jpg",1500,750,false]},"uagb_author_info":{"display_name":"Pankaj Kumar","author_link":"https:\/\/codeforgeek.com\/author\/pankaj\/"},"uagb_comment_info":0,"uagb_excerpt":"We use Node.js to build web application backend and one of the use cases that comes often is a file upload feature. In this tutorial, we are going to learn and build an application that can let user upload multiple files using Node.js. LIVE DEMO DOWNLOAD Our application : I am going to develop same&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/1890","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/69"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=1890"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/1890\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/5866"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=1890"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=1890"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=1890"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}