Integrating file upload feature to a nodejs project

Integrating file upload feature to a nodejs project

As a web developer or backend engineer, you may often get into a situation where you have to allow the users to upload some files to a server through the application you are working on. This can be images, videos, documents or anything. There are tons of paid saas products or cloud storage solutions available in the market to solve this problem but what if I tell you that there is an open-source npm package which can help you out with this? In Node js, there is a popular package named multer which can handle file uploads in your application.

Multer allows you to handle HTTP requests with enctype="multipart/form-data" which is used for file uploads. Here enctype is an HTML attribute which means an encoding type used in HTML forms and the multipart/form-data is the protocol for sending form data to the server in multiple parts due to the large size of files to be uploaded.

Multer is very easy to use and Integrating it into a Node js application is very simple and can be done using a few lines of code.

In this article, we will be looking through the process of integrating multer and also discuss the various use cases and customization features.

Prerequisites

  • Nodejs installed in your machine

  • Any prefered code editor I'm using vs code

  • express js app. Check out the template here

Setup the express app from the above template

  • Open up the terminal and paste the below command

    git clone https://github.com/kumar-kalyan/express-app.git
    

    This will copy all the template files to your local machine

  • Now enter the root directory of the template

    cd express-app
    

    • Install all the directories using npm install

Getting started

  • Open up the terminal in the root directory and use the below command to add multer to the Node js project
npm install multer
  • Once the installation is completed now you need to import the multer module into your project using the require keyword and finally set up the middleware. This can be done inside the server.js file or any separate module as per project structure.

    Middleware in Express is a special function which has access to the request object, response object and the next middleware function within the application request-response lifecycle.

  • In this article, we will implement multer middleware in the server.js file.

    const multer = require('multer')
    

    The above code shows how to import a module in a Node js project.

Setup the storage function

  • Now let's setup storage function inside the multer module to store the uploaded files

    // SET STORAGE
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, 'uploads/')
        },
        filename: function (req, file, cb) {
            cb(null, file.fieldname + '-' + Date.now() + ".png")
        }
    })
    var upload = multer({ storage: storage })
    

    multer has a diskStorage function which takes two parameters named destination and filename the former is responsible for handling the upload destination which is set to a folder named uploads and the latter is responsible for handling the name of the file which is to be uploaded. For the file name, we are taking the file.fieldname which can be accessed from the request object and followed by a concatenation of the current date using the javascript date object lastly adding the filename type will store all the uploaded files in png format

after that, we are configuring the upload variable and setting the storage inside the multer function.

Create a POST request for file upload

  • Now let's create the post request for uploading files

    app.post('/profile', upload.single('upfile'), function (req, res) {
        // req.file is the `avatar` file
        try {
            res.json({
                "name": req.file.originalname,
                "type": req.file.mimetype,
                "size": req.file.size
            })
        }
        catch (err) {
            res.json({ "err": err })
        }
        // req.body will hold the text fields, if there were any
    })
    

    So in the above request, we are passing the upload.single middleware function and inside it specifying the name of the file. On successful upload, we are sending a JSON response to the user and on errors, we are sending the error message as a JSON response. We are using try catch block to handle errors

Let's build the front end for file upload

  • Now let's build the front end for the file upload

    Create a folder named views inside it create a file named index.html

    Inside the index.html create a simple form using the following code

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <form action="/profile" method="post" enctype="multipart/form-data">
            <input type="file" name="upfile" />
            <input type="submit" value="upload" class="btn btn-default">
          </form>
    </body>
    </html>
    

    Make sure to specify the attribute of enctype="multipart/formdata" which I have mentioned earlier in this article. create an input element of type file and name to upfile this can be anything of your choice but make sure to keep it the same which we have used in the upload middleware in the server.js file. In the form make the method attribute to a POST request and the action attribute to /profile which is our route to the POST request for file upload.

Setup server.js for rendering index.html

  • Now let's create a basic GET request and will send this file to the user using the process.cwd in Node Js. cwd stands for the current working directory is a function inside the Node Js process module and is used to work with files. Importing the process module can be done by following a piece of code

    const process = require('process');
    

    The GET request can be defined like this

    app.get('/', function (req, res) {
        res.sendFile(process.cwd() + '/views/index.html');
    });
    

    So the above code is responsible for sending the index.html to the user.

    Let's check the result

    • Start the server using

      node server.js
      

  • open your browser and open the link http://localhost:5000/

  • Click on the Choose File button to select files

  • Now click on upload

    You must see a response like this

Conclusion

Overall, Multer makes it easy to add file upload functionality to your Node.js application. Whether you are working on a small personal project or a large enterprise application, Multer has you covered. There are many customizing options available for multer like multiple file uploads, specifying the size, etc. which can be found on the multer's NPM page. Make sure to share this article with your peers and reach out for any queries. Follow Documatic for amazing content like this one.

Happy Coding :)