How to upload file with progress bar using Node.js ?
File Upload in NodeJS means to move files from the client location to the server location. A Progress bar is a visual component that changes and updates according to the total file upload percentage. Here we are going to make a local server and upload files to a destination folder by increasing the bar length as the upload progresses.
Formidable Module: It is a Node.js module for parsing form data, mainly used for file uploads.
Install: Go to the project directory and run the command:
npm install formidable
Steps to Create Server:
Step 1: First create an ‘index.html’ file which will act as the frontend for the client. A sample code is given below. We create an empty component progressUpload which will be updated only after files are selected to upload.
Step 2: Create a ‘uploader.js’ which will open a pop-up to upload files and display a progress bar. The JS code is given below.
First, we create an input element for the files and attach that to our browse button on the frontend using the addEventListener function. When a new file is selected the file details are sent using FormData() format.
To update Progress Bar we addEventlistener to it and update its value in percentage. The progress bar is added to ‘index.html’ by creating two div components in createProgressbar( ) function.
Step 3: Now create the main server file ‘server.js’ which will upload the files to the destination and send the requested resources for a webpage to the client-side. We have four different URL request types for HTML, CSS, JS, and upload. Using the Nodejs file system module ‘fs’ move the file to a new location.
Note: In ‘var upd ‘ add your machine destination address.
Step 4: Finally create a stylesheet ‘index.css’ to format the display of the progress bar.
Step 5: Update the NodeJS module by installing npm and run the project by running the command:
Step 6: Go To URL http://localhost:7777/index.html and upload the file.