Handling file upload in Nodejs

filuploadinreactjs
filuploadinreactjs

Node.js is an open-source JavaScript runtime environment for developing variety of server tools and applications commonly used for creation of backend apis. In today’s tutorial we are going to handle file upload to nodejs server using express framework. We are going to continue from login and registration apis we created in the previous article which can be found here.

We are going to use multer middleware to handle file upload,async module to handle file operations and node cmd in case you need to run terminal commands in nodejs. So let’s install them by running the following command:

Next edit server.js file as follows:

We have imported multer module in server.js and set temporary file storage destination on lines 9 & 10.Next we created a fileupload route which will handle file upload requests to server.We have set any option in multerupload to allow uploading of any types of files. You can find other options for specific files here. Now I have created another routes file called fileroutes.js within routes folder to handle file uploading and listing tasks and called fileupload function from that file on line 31. The file structure now is as follows:

├── package.json
├── routes
│   ├── fileroutes.js
│   └── loginroutes.js
├── server.js

Now we are going to assume that user sends multiple files from frontend at a time in the form of an array. Let us now move forward to define fileupload handler in fileroutes.js file.

In this file we are going to first store files retrieved from client request in local filesArray variable.

If you print console output of req.files then it will show following format:

‘async.each’ method take array as an input,iterate over each item and then uses callback to do processing after all items have been iterated(More detailed explanation here). We iterate through the array using async each method since it allows us to get final callback once all the files in the array have finished processing.In our case we have sent response back to client in final callback and removed temporary files created in fileupload folder by multer module.

Going a step further we can store the files in some specific path using fs module in async each module as follows:

In this case we have used async waterfall method within async.each to execute series of tasks synchronously. Async waterfall method takes array of functions as an input, runs them one after another and handles final callback once all functions have finished execution synchronously. One key thing to keep in mind is async.each operation iterates through array items parallely while waterfall ensures that each parallel iteration will first readlfile from file path and then the file is written to writepath. Simply speaking even if you pass same 10 files to server multiple times the order in which they will be processed will differ each time however every time the server will first read the file data and then write it to file path.

You can find the complete fileroutes.js code in github gist uploaded here.

Bonus Tip:

You can modify the async.waterfall method to store files in database or server storage.

I have written a tutorial using reactjs to create simple frontend website which sends files to node server which can be found here.

You can check out the tutorial on creating admin dashboard to keep track of number of users and number of files uploaded by users here.

Connect Deeper:

In the next tutorial I will cover how to store and retrieve the files to cloud storage in nodejs using openstack and docker so follow our facebook page to get notified about similar posts in the future: Technoetics or subscribe to our mailing list:

Technoetics newsletter

Get notified about upcoming articles,tips and tricks personally hand-delivered to your inbox

Share post-
About Saurabh Mhatre 70 Articles
Currently working in web and hybrid application development
  • Kashikoi Jōkyaku

    Hi,
    How did the upload behave correctly?

    • smhatre59

      Is there something wrong with the code or was there any issue with the upload functionality stated in the tutorial? Please feel free to explain the issue in detail so that I might be able to modify tutorial accordingly 😀

  • Uday Saini

    Hey its working good.

    But can you tell me how to add Progress bar to it ?! Do you have the code to it ? and also what can we do to send file to server?

    • smhatre59

      You might have to use buffers in nodejs to send data as streams to file server using form data npm module:
      https://www.npmjs.com/package/form-data
      https://github.com/request/request#multipartform-data-multipart-form-uploads
      In the frontend part you can use any kind of progress bar to track file upload progress like:
      https://github.com/abdennour/react-progressbar
      https://github.com/milworm/react-progress-2