

{"id":114698,"date":"2023-06-10T09:00:24","date_gmt":"2023-06-10T03:30:24","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=114698"},"modified":"2023-06-10T10:14:24","modified_gmt":"2023-06-10T04:44:24","slug":"expressjs-file-upload","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/","title":{"rendered":"How to Handle File Upload in ExpressJS?"},"content":{"rendered":"<p>Express.js is a web framework for Node.js that allows developers to easily build scalable web applications. One common feature of web applications is the ability for users to upload files, such as images or documents.<br \/>\nIn this article, we will take a look at how to handle file uploads using Express.js.<\/p>\n<h3>How to Handle File Upload in ExpressJS?<\/h3>\n<p>There are a few different ways to handle file uploads in Express.js, but we will be focusing on using the multer middleware. Multer is a middleware for handling form-data, which is used for uploading files. It makes it easy to handle file uploads and provides various options for configuring how the uploaded files are handled.<\/p>\n<h4>Multer Installation<\/h4>\n<p>First, let&#8217;s install multer using npm:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">npm install multer\r\n<\/pre>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/multer-install.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-114965\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/multer-install.webp\" alt=\"multer install\" width=\"512\" height=\"144\" \/><\/a><\/p>\n<h4>Multer Usage<\/h4>\n<p>To use multer in an Express.js application, we need to require it and create an instance of the multer middleware. We can then use this middleware in a route handler to handle file uploads.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const express = require('express');\r\nconst multer = require('multer');\r\n\r\nconst app = express();\r\n\r\n\/\/ Create an instance of multer middleware\r\nconst upload = multer({ dest: 'uploads\/' });\r\n\r\n\/\/ Route handler for file upload\r\napp.post('\/upload', upload.single('file'), (req, res) =&gt; {\r\n  \/\/ Handle the uploaded file here\r\n});\r\n<\/pre>\n<p>In this example, we have created an instance of multer middleware and specified the destination folder where uploaded files will be stored. We have then defined a route handler for the \/upload endpoint, which uses the upload.single() method to handle a single file upload. The name of the file input field in the HTML form is specified as the argument to the single() method.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/creating-instance.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-114966\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/creating-instance.webp\" alt=\"creating instance\" width=\"512\" height=\"251\" \/><\/a><\/p>\n<h4>Handling the uploaded file<\/h4>\n<p>Once a file has been uploaded, it will be stored in the destination folder specified in the multer configuration. We can then access the uploaded file using the req.file object in the route handler.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/handling-uploaded-file-.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-114967\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/handling-uploaded-file-.webp\" alt=\"handling uploaded file\" width=\"512\" height=\"103\" \/><\/a><\/p>\n<h4>Running project on node<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">app.post('\/upload', upload.single('file'), (req, res) =&gt; {\r\n  const file = req.file;\r\n\r\n  \/\/ Do something with the uploaded file\r\n});\r\n<\/pre>\n<p>The req.file object contains various properties related to the uploaded file, such as the file name, size, and MIME type. We can use these properties to handle the uploaded file as needed.<\/p>\n<h3>Information that the uploaded file contains<\/h3>\n<p>When it comes to file uploads in an Express.js application, the req.files.foo object contains a variety of information about the uploaded file. Here&#8217;s a breakdown of the different properties available in the req.files.foo object:<\/p>\n<ul>\n<li><strong>name:<\/strong> The original name of the uploaded file.<\/li>\n<li><strong>data:<\/strong> The raw binary data of the file.<\/li>\n<li><strong>size:<\/strong> The size of the file in bytes.<\/li>\n<li><strong>encoding:<\/strong> The encoding type of the file.<\/li>\n<li><strong>tempFilePath:<\/strong> The path to the temporary file where the uploaded file is stored.<\/li>\n<li><strong>truncated:<\/strong> A Boolean value that indicates whether the file was truncated during the upload.<\/li>\n<li><strong>mimetype:<\/strong> The MIME type of the file, as determined by the uploaded file&#8217;s extension.<\/li>\n<\/ul>\n<p>In addition to these properties, the req.files.foo object may also contain other properties depending on the configuration of the file upload middleware used in the Express.js application. For example, if the dest property is set in the multer middleware configuration, the req.files.foo object may also contain a destination property that specifies the directory where the uploaded file should be stored.<\/p>\n<h3>Multiple file upload in Express JS<\/h3>\n<p>If we want to allow users to upload multiple files at once, we can use the upload.array() method instead of the upload.single() method. The array() method takes the name of the file input field as its argument.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">app.post('\/upload', upload.array('files'), (req, res) =&gt; {\r\n  const files = req.files;\r\n\r\n  \/\/ Handle the uploaded files here\r\n});\r\n<\/pre>\n<p>In this example, we have used the upload.array() method to handle multiple file uploads. The uploaded files are stored in the req.files array, which we can then use to handle each file individually.<\/p>\n<h3>Express JS File validation<\/h3>\n<p>Multer provides various options for validating uploaded files, such as file type and size restrictions. We can specify these options in the multer configuration object.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const storage = multer.diskStorage({\r\n  destination: (req, file, cb) =&gt; {\r\n    cb(null, 'uploads\/');\r\n  },\r\n  filename: (req, file, cb) =&gt; {\r\n    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);\r\n    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));\r\n  },\r\n});\r\n\r\nconst upload = multer({\r\n  storage: storage,\r\n  limits: {\r\n    fileSize: 1024 * 1024 * 5, \/\/ 5 MB\r\n  },\r\n  fileFilter: (req, file, cb) =&gt; {\r\n    const allowedMimeTypes = ['image\/jpeg', 'image\r\nif (allowedMimeTypes.includes(file.mimetype)) {\r\ncb(null, true);\r\n} else {\r\ncb(new Error('Invalid file type.'));\r\n}\r\n},\r\n});\r\n<\/pre>\n<p>In this example, we have specified a disk storage engine for multer using the diskStorage() method. We have also set a file name using a unique suffix and the original file extension.<\/p>\n<p>We have then specified a file size limit of 5MB using the limits option, and a file type filter using the fileFilter option. The fileFilter option takes a function that is called for each uploaded file, and returns an error if the file type is not allowed.<\/p>\n<h3>Conclusion<\/h3>\n<p>Handling file upload is a common requirement in web applications and Express.js makes it easy to handle this task using the multer middleware. With multer, we can easily handle single or multiple file uploads, validate uploaded files, and store them in a destination folder.<\/p>\n<p>However, it&#8217;s important to remember that file uploads can be a security risk, and we should always validate uploaded files carefully to prevent any potential security vulnerabilities.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Express.js is a web framework for Node.js that allows developers to easily build scalable web applications. One common feature of web applications is the ability for users to upload files, such as images or&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":114801,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27631],"tags":[27667,27666],"class_list":["post-114698","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-express-js-tutorials","tag-file-upload-in-express-js","tag-file-upload-in-expressjs"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How to Handle File Upload in ExpressJS? - DataFlair<\/title>\n<meta name=\"description\" content=\"ExpressJS makes it easy to handle file upload using the multer middleware. See how to handle single and multiple file upload in Express JS.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Handle File Upload in ExpressJS? - DataFlair\" \/>\n<meta property=\"og:description\" content=\"ExpressJS makes it easy to handle file upload using the multer middleware. See how to handle single and multiple file upload in Express JS.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-06-10T03:30:24+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-06-10T04:44:24+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-file-upload.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Handle File Upload in ExpressJS? - DataFlair","description":"ExpressJS makes it easy to handle file upload using the multer middleware. See how to handle single and multiple file upload in Express JS.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/","og_locale":"en_US","og_type":"article","og_title":"How to Handle File Upload in ExpressJS? - DataFlair","og_description":"ExpressJS makes it easy to handle file upload using the multer middleware. See how to handle single and multiple file upload in Express JS.","og_url":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-06-10T03:30:24+00:00","article_modified_time":"2023-06-10T04:44:24+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-file-upload.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"How to Handle File Upload in ExpressJS?","datePublished":"2023-06-10T03:30:24+00:00","dateModified":"2023-06-10T04:44:24+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/"},"wordCount":757,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-file-upload.webp","keywords":["File Upload in Express JS","File Upload in ExpressJS"],"articleSection":["Express JS Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/","url":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/","name":"How to Handle File Upload in ExpressJS? - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-file-upload.webp","datePublished":"2023-06-10T03:30:24+00:00","dateModified":"2023-06-10T04:44:24+00:00","description":"ExpressJS makes it easy to handle file upload using the multer middleware. See how to handle single and multiple file upload in Express JS.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-file-upload.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-file-upload.webp","width":1200,"height":628,"caption":"expressjs file upload"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/expressjs-file-upload\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Express JS Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/express-js-tutorials\/"},{"@type":"ListItem","position":3,"name":"How to Handle File Upload in ExpressJS?"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114698","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=114698"}],"version-history":[{"count":4,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114698\/revisions"}],"predecessor-version":[{"id":114968,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114698\/revisions\/114968"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/114801"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=114698"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=114698"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=114698"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}