File Upload with Progress Bar in JavaScript is a technique that allows users to upload one or multiple files to a server with a progress bar indicating the current progress of the upload. This feature provides a more user-friendly experience compared to a traditional file upload where the user has to wait for the upload to complete without any indication of the progress.
To implement a file upload with a progress bar in JavaScript, you can use the HTML5 File API
and XMLHttpRequest
(or the fetch API) to send the files to a server. The File API
allows you to access and manipulate the files selected by the user, while XMLHttpRequest
(or fetch) is used to send the files to the server. The XMLHttpRequest.upload
property is used to monitor the progress of the upload. You can then update the progress bar element in the HTML with the current progress.
It’s a good way to show the progress of the file upload to the user, which gives a better understanding of how much time it will take to upload the file and also to show that the file is uploading and not stuck somewhere.
File Upload with Progress Bar in HTML CSS JavaScript
To create a file upload with a progress bar in HTML, CSS, and JavaScript, you will need to use the following steps:
- Create an HTML form with a file input element, a submit button, and a div container for the progress bar.
- Use CSS to style the form, file input, and progress bar.
- Use JavaScript to listen for the form’s submit event, retrieve the selected file, and create an XMLHttpRequest object to upload the file.
- Use the XMLHttpRequest object’s onprogress event to listen for updates on the upload progress and update the progress bar accordingly.
- Handle the form’s submit event and start the file upload by calling the XMLHttpRequest object’s open and send methods.
Here is an example of how you can implement this:
Step 1: HTML of File Upload with Progress Bar
The form has an id
attribute of “upload-form” which allows it to be selected using JavaScript.
The form includes an input element of type “file” with an id
attribute of “file-input”, this element allows the user to select a file from their computer to upload. The form also includes a submit input element with a value of “Upload” which submits the form and triggers the file upload process.
The form also includes a div element with a class of “progress-bar” which acts as a container for the progress bar. Inside the container, there is another div element with an id
attribute of “progress” which is used to represent the progress bar. The width of this element will be updated as the file uploads to indicate the progress.
Once the form is submitted, JavaScript code can be used to access and manipulate the elements within the form. The file input element can be used to get the selected file, the progress bar element can be used to display the progress of the upload.
It’s a simple but effective way to create an upload form, it uses the standard HTML form
and input
elements, and the JavaScript code simply adds functionality to the form.
Step 2: CSS Code
.progress-bar {
width: 100%;
height: 20px;
background-color: #ddd;
}
#progress {
width: 0%;
height: 100%;
background-color: #4CAF50;
}
Step 3: JavaScript code for File Upload with Progress Bar
The code first selects the form, file input, and progress bar elements in the HTML using their respective id
attributes.
An event listener is then added to the form to listen for the submit
event. When the form is submitted, the event’s default behavior is prevented using e.preventDefault()
to avoid reloading the page.
The code then retrieves the selected file from the fileInput
element using the files
property, creates a new FormData
object, and appends the file to it. This FormData
object will be sent to the server as part of the request.
The code then creates a new XMLHttpRequest
object, opens a POST request to the server-side script ‘/upload’, and sets the upload.onprogress
event to handle the progress of the upload. The progress event is triggered periodically as the file is being uploaded to the server. The event contains the loaded
and total
properties, which indicate the number of bytes that have been uploaded and the total number of bytes to be uploaded, respectively. The code uses these properties to calculate the percentage of the upload that is complete and updates the width of the progress bar element to reflect the progress.
Finally, the FormData
object is sent to the server using the send
method of the XMLHttpRequest
object.
const form = document.getElementById('upload-form');
const fileInput = document.getElementById('file-input');
const progressBar = document.getElementById('progress');
form.addEventListener('submit', e => {
e.preventDefault();
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.upload.onprogress = e => {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
progressBar.style.width = `${percentComplete}%`;
}
};
xhr.send(formData);
});
Note: The above code is just an example and you need to handle the server side code as well to handle the file upload.
Multiple File Upload with Progress Bar in JavaScript
To implement a multiple file upload with a progress bar in JavaScript, you can use the HTML5 File API
and XMLHttpRequest
(or the fetch API) to send the files to a server.
Here’s an example of how you can use the File API
and XMLHttpRequest
to upload multiple files with a progress bar:
Step 1: HTML of Multiple File Upload
The form includes an input element of type “file” with an id
attribute of “file-input” and the multiple attribute, this element allows the user to select one or more files from their computer to upload. The form also includes a submit button element with a value of “Upload” which submits the form and triggers the files upload process.
The form also includes a progress element with an id
attribute of “progress-bar” which acts as a progress bar. This element’s value attribute is set to “0” and max attribute is set to “100” and it’s used to represent the progress of the upload. The value of this element will be updated as the files upload to indicate the progress.
Step 2: JavaScript for Multiple File Upload with Progress Bar
The code first selects the form element with an id of “file-form” using the getElementById
method and adds an event listener to listen for the submit
event. When the form is submitted, the event’s default behavior is prevented using event.preventDefault()
to avoid reloading the page.
Then it retrieves the selected files from the file input element with an id of “file-input” using the files
property. A new FormData
object is then created and a for loop is used to iterate through the files array. The files are then appended to the FormData
object using the append
method.
A new XMLHttpRequest
object is then created and the open
method is used to open a POST request to the server-side script “upload.php”. The onload
event is then set to handle the server response. If the status of the response is 200, which indicates a successful upload, an alert message is shown to the user. If the status is not 200, an error message is shown.
The upload.onprogress
event is then set to handle the progress of the upload, it’s triggered periodically as the files are being uploaded to the server. The event contains the loaded
and total
properties, which indicate the number of bytes that have been uploaded and the total number of bytes to be uploaded, respectively. The code uses these properties to calculate the percentage of the upload that is complete and updates the value attribute of the progress bar element with an id of “progress-bar” to reflect the progress.
Finally, the FormData
object is sent to the server using the send
method of the XMLHttpRequest
object.
document.getElementById("file-form").addEventListener("submit", function(event) {
event.preventDefault();
var files = document.getElementById("file-input").files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("files[]", files[i]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php");
xhr.onload = function() {
if (xhr.status === 200) {
alert("Upload successful!");
} else {
alert("Error uploading files. Please try again.");
}
};
xhr.upload.onprogress = function(event) {
var progress = (event.loaded / event.total) * 100;
document.getElementById("progress-bar").value = progress;
};
xhr.send(formData);
});
Hopefully from this article you have learned how to create File Upload with Progress Bar. Here I have shared two types of designs with you.