When we are uploading a file, a progress
event is periodically fired which indicates the amount of content that has been uploaded to the server.
The progress
event is triggered for the upload
property of the XHR request object. So, we will bind the progress
event for the upload
property.
Inside this progress event, we have two properties:
loaded:
The size of the file that has been uploaded to the server.
total:
The total size of the file that is being uploaded.
Let's create an example to upload a file using the XHR and display the percentage of the file uploaded by listening to the progress
event.
In the HTML section, from lines 9–15, we added 4 elements:
File upload input element.
A button with text upload file
which will trigger the file upload operation.
A progress bar element to indicate the file upload progress.
A paragraph element to display the file size upload progress.
In the JavaScript section:
Lines 18–42: We create the uploadFile
function. This function will be triggered when an upload button is clicked.
Lines 20–25: Get the selected file from the file input
element and print the file type, name, and size.
Line 29: We create a FormData
object and add the selected file to it. This is for sending the file with the request.
Line 32: We create an XMLHttpRequest
object with the name ajax
.
Line 35: Add the progress
event to the upload property of the ajax
object. This event is triggered periodically when the data is uploaded to the request object. For this event, in the event object, we will get the total size of the file and the size of the file that is loaded to the request. Based on these values we update the progress bar.
Line 38: Initialize the ajax object with request method type (POST
) and the URL to which the request is to be sent.
Line 41: We send the request with the form data which contains the file that is to be uploaded.