<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Chinwendu Enyinna</title>
    <description>The latest articles on DEV Community by Chinwendu Enyinna (@wendeee).</description>
    <link>https://dev.to/wendeee</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1074863%2Faec028cd-161c-41cf-bb0f-f10927d739be.jpeg</url>
      <title>DEV Community: Chinwendu Enyinna</title>
      <link>https://dev.to/wendeee</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/wendeee"/>
    <language>en</language>
    <item>
      <title>How to Upload a File to a Nodejs Server Using Multer</title>
      <dc:creator>Chinwendu Enyinna</dc:creator>
      <pubDate>Mon, 01 May 2023 13:20:33 +0000</pubDate>
      <link>https://dev.to/wendeee/how-to-upload-a-file-to-a-nodejs-server-using-multer-3b4e</link>
      <guid>https://dev.to/wendeee/how-to-upload-a-file-to-a-nodejs-server-using-multer-3b4e</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;File upload is a common feature in many web applications. This feature allows users to share documents, photos, videos, and other types of files.&lt;/p&gt;

&lt;p&gt;Multer is a Nodejs middleware package that provides a simple and flexible way to handle file uploads allowing you to customize the file storage location, validate uploaded files, and much more.&lt;/p&gt;

&lt;p&gt;In this tutorial, I will demo how to use Multer to handle file uploads in a NodeJS application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisite
&lt;/h2&gt;

&lt;p&gt;To follow along with this tutorial, you should have the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;NodeJs installed on your device.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A basic understanding of NodeJs and Express&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is Multer?
&lt;/h2&gt;

&lt;p&gt;Multer is a Nodejs middleware package for handling &lt;code&gt;multipart/form-data&lt;/code&gt;. It is similar to &lt;code&gt;body-parser&lt;/code&gt; which is also a middleware used to parse incoming HTTP requests in the request body and extract data in the form of JSON or URL-encoded data.&lt;/p&gt;

&lt;p&gt;Although &lt;code&gt;body-parser&lt;/code&gt; can technically parse the file upload data in the request body if it is sent as base64-encoded data, it is not efficient for handling large files. Multer is primarily designed for this and can handle large files more efficiently than sending them in the request body.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Set Up
&lt;/h2&gt;

&lt;p&gt;Create a project folder and navigate into it via your terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir fileUpload &amp;amp;&amp;amp; cd fileUpload
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Initialize the project by running:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm init -y&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;This will generate a &lt;code&gt;package.json&lt;/code&gt; file that will contain metadata about the project and the dependencies you will install.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--v7f9J_9v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sz3mvnaoej00stmlmzfs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--v7f9J_9v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sz3mvnaoej00stmlmzfs.png" alt="A package.json file" width="629" height="267"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Install the required packages. For this demo, you would need Express, Multer, and Postman.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://expressjs.com/"&gt;Express&lt;/a&gt; - Is an unopinionated web framework for Nodejs used for creating HTTP web servers. Express provides an easy-to-use abstracted API built on Nodejs for interacting with the web server.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/multer"&gt;Multer&lt;/a&gt; - Is a Nodejs middleware package designed specifically to handle file uploads.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.postman.com/"&gt;Postman&lt;/a&gt; - Is a software application used to test API endpoints.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i express multer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create the entry file, &lt;code&gt;index.js&lt;/code&gt; and open the project folder in your preferred text editor. For this tutorial, I'm using VScode.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;touch index.js &amp;amp;&amp;amp; code .
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;code .&lt;/code&gt; &lt;em&gt;opens up the project folder in vs code&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;index.js&lt;/code&gt; file, initialize an express app, and set up a simple Nodejs server that the browser would communicate with.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//import packages
const express = require("express");

//create express app
const app = express();

app.get('/', (req, res) =&amp;gt; {
    res.send('File uploads with Nodejs')
})

//configure port for server
app.listen("3004", () =&amp;gt; {
  console.log("server is running on port 3004");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How does Multer process file upload behind the scenes?
&lt;/h2&gt;

&lt;p&gt;Multer is a middleware for handling file uploads in Nodejs. Behind the scenes, Multer uses the "multipart/form-data" encoding for file uploads which is the standard format for HTML forms that include file inputs.&lt;/p&gt;

&lt;p&gt;When a client sends a POST request with a "multipart/form-data" content-type and a file input, Multer intercepts the request before it reaches the route handler and begins parsing the form data. It uses the &lt;em&gt;busyboy&lt;/em&gt; library - a streaming parser that can handle large files without consuming too much memory - for parsing the form data. As the form data is being parsed, Multer extracts the file data and stores it in memory or on disk, depending on you set up the configuration. Also, Multer adds a &lt;code&gt;files&lt;/code&gt; property on the request object which contains an array of objects representing the uploaded files.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note, for single file upload, it adds &lt;code&gt;file&lt;/code&gt; property.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Once Multer has finished parsing the form data and storing the files, it calls the next middleware in the stack allowing the route handler to access the uploaded files through the files property on the request object.&lt;/p&gt;

&lt;h2&gt;
  
  
  Configuring Multer in the Server
&lt;/h2&gt;

&lt;p&gt;Multer comes shipped with a number of configuration options such as setting the file size limits, defining the file naming conventions, filtering the type of files to be uploaded, and specifying a destination directory for storing the uploaded files. These options can be used to customize Multer's behavior to fit the specific need of your application.&lt;/p&gt;

&lt;p&gt;Here's an example of how you can configure Multer in your Express server to accept files from the client.&lt;/p&gt;

&lt;p&gt;Import the Multer package in the &lt;code&gt;index.js&lt;/code&gt; file and add the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multer = require('multer');
//require path module
const path = require('path')

//configure storage 
const storage = multer.diskStorage({
    destination: function(req, file, cb){
        cb(null, './public/images')
    },
    filename: function(req, file, cb){
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, uniqueSuffix + path.extname(file.originalname))
    }
})

//create middleware
const upload = multer({storage: storage})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: You should first create the directory where you want to upload the files to. This is what you specify in the destination option. For this demo, I created an images folder in the public directory.&lt;/p&gt;

&lt;p&gt;Next, create a route handler for the file upload.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.post("/", upload.single('image'), (req, res) =&amp;gt; {
    console.log(req.file)
  res.send("File uploaded successfully");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this route handler, the upload middleware is called and passed the name of the field in the form which the file is uploaded from - in this case,image .&lt;/p&gt;

&lt;p&gt;Multer also lets you upload multiple files using &lt;code&gt;upload.array()&lt;/code&gt; .&lt;/p&gt;

&lt;p&gt;Open Postman to test the implementation so far.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ezHYzDYM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nt90qnemivhufxtrvjz2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ezHYzDYM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nt90qnemivhufxtrvjz2.png" alt="Screenshot of result in postman" width="800" height="374"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;At this point, you should see the uploaded file in the destination folder you specified.&lt;/p&gt;

&lt;p&gt;Alternatively, if you want to test this using an HTML form on the frontend, you should include the enctype attribute in the form and set its value to multipart/form-data like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;lt;form method="POST" action="/" enctype="multipart/form-data"&amp;gt;
        &amp;lt;input type="file" name="image"&amp;gt;
        &amp;lt;input type="submit"&amp;gt;
    &amp;lt;/form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to Validate Uploaded Files
&lt;/h2&gt;

&lt;p&gt;Multer has a built-in &lt;code&gt;fileFilter&lt;/code&gt; method which can be used to validate the uploaded files. With this method, you can define conditions that will run specific checks on the file. For example, say you only want jpeg, jpg or png file types to be uploaded. You can configure a file filter option like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const filterOption = (req, file, cb) =&amp;gt; {
     if (file.mimetype == 'image/jpeg' || file.mimetype == 'image/png' || file.mimetype == 'image/jpg') {
        cb(null, true);
    } else {
        cb(null, false);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function checks the &lt;code&gt;mimetype&lt;/code&gt; property of the &lt;code&gt;file&lt;/code&gt; object to determine whether the uploaded file is an image of type jpeg, png, or jpg. If the file is one of these types, the function calls the &lt;code&gt;cb&lt;/code&gt; callback with the first argument null and the second argument as &lt;code&gt;true&lt;/code&gt; which means that the file should be accepted and passed on to the next middleware or route handler.&lt;/p&gt;

&lt;p&gt;However, If the file is not one of the accepted types, the function calls the &lt;code&gt;cb&lt;/code&gt; callback with the first argument &lt;code&gt;null&lt;/code&gt; and the second argument as &lt;code&gt;false&lt;/code&gt; which means that the file should be rejected and an error message should be sent to the user.&lt;/p&gt;

&lt;p&gt;To include this option in the previous Multer configuration, edit the &lt;code&gt;upload&lt;/code&gt; middleware function to look this way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const upload = multer({storage: storage, fileFilter: filterOption})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The final code should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const multer = require("multer");
const path = require('path')
const app = express();
app.use(express.static("public"));
const storage = multer.diskStorage({
    destination: function(req, file, cb){
        cb(null, './public/images')
    },
    filename: function(req, file, cb){
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, uniqueSuffix + path.extname(file.originalname))
    }
})

const upload = multer({storage: storage, fileFilter: filterOption})

app.get('/', (req, res) =&amp;gt; {
  res.send('File uploads with Nodejs')
});

app.post("/", upload.single('image'), (req, res) =&amp;gt; {
    console.log(req.file)
  res.status(200).json({status: 'success', message: "Upload successful!"});
});

app.listen("3004", () =&amp;gt; {
  console.log("server is running on port 3004");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this tutorial, you have learned the basics of file uploading in Nodejs including how to set up and configure Multer to handle file uploads. You also learned how to customize the uploading process based on your specific needs. By following the steps outlined in this post, you can quickly and easily integrate Multer into your Nodejs application.&lt;/p&gt;

&lt;p&gt;Thank you for reading!&lt;/p&gt;

&lt;p&gt;Happy coding :)&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
