Java Script to Show File Upload Progress
In my previous posts, nosotros discovered How to Use HTML5 File Elevate & Drop, Open Files Using JavaScript and Asynchronously Upload Files Using Ajax. In the terminal part of this series, we cover the most exciting role of the process: graphical progress bars!
File upload progress bars provide essential user feedback but they've been notoriously difficult to implement. Until now that is. Both Firefox and Chrome support the XMLHttpRequest2 object which offers a progress issue handler. Just commencement, let'southward consider how our progress bar will exist implemented…
The HTML5 progress tag
The new progress
tag provides 2 attributes:
- value: the current progress value
- max: the value at completion
The tag would have been ideal in this demonstration and, although it's supported in Chrome, it'south only just appeared in Firefox half dozen. In addition, neither browser offers many styling properties so I dropped it in favor of a standard p
tag. This is appended as a child to a div
with the ID "progress".
Styling the Progress Bar
Our p
tag will evidence the file name in a bordered box which is 250px in size:
#progress p { display: block; width: 240px; padding: 2px 5px; margin: 2px 0; border: 1px inset #446; border-radius: 5px; }
For the green bar itself, I created a graphic which was twice equally wide as the progress element (500px). The left 250px is colored and the correct 250px is transparent:
This graphic is used as a background epitome for the progress bar and positioned at "X% 0" where Ten% indicates the proportion which is REMAINING (not COMPLETED), i.eastward.
- progress starts from "groundwork-position: 100% 0", i.e. 100% remaining
- progress ends at "background-position: 0% 0", i.e. nothing's remaining
- "background-position: 30% 0" means seventy% has been completed:
A solid color is applied by setting a grade when the upload succeeds or fails:
#progress p.success { background: #0c0 none 0 0 no-repeat; } #progress p.failed { groundwork: #c00 none 0 0 no-repeat; }
Implementing the Progress Bar in JavaScript
We tin now modify our UploadFile() office. When a valid JPG file is encountered, we append a new p
tag to the #progress chemical element and add the file proper noun every bit text:
// upload JPEG files function UploadFile(file) { var xhr = new XMLHttpRequest(); if (xhr.upload && file.type == "paradigm/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) { // create progress bar var o = $id("progress"); var progress = o.appendChild(certificate.createElement("p")); progress.appendChild(document.createTextNode("upload " + file.proper name));
We now require a "progress" event handler function. This receives an object with .loaded and .total properties — a little math is necessary to calculate the new backgroundPosition:
// progress bar xhr.upload.addEventListener("progress", function(e) { var pc = parseInt(100 - (eastward.loaded / e.total * 100)); progress.style.backgroundPosition = pc + "% 0"; }, false);
If you're familiar with Ajax, you'll recognise the onreadystatechange event handler. This determines when the upload has completed and styles the progress bar accordingly (sets a class of "success" if the upload was successful):
// file received/failed xhr.onreadystatechange = role(e) { if (xhr.readyState == 4) { progress.className = (xhr.status == 200 ? "success" : "failure"); } };
Finally, we send the file to our PHP server as before:
// kickoff upload xhr.open up("Mail", $id("upload").action, true); xhr.setRequestHeader("X-FILENAME", file.proper noun); xhr.ship(file); } }
We finally have a solution which:
- enables file dragging and dropping onto a spider web page element
- analyzes and displays dropped files on the customer
- asynchronously uploads files to the server
- shows a graphical progress bar during upload
- uses progressive enhancement to back up most browsers
- is coded without requiring a JavaScript library.
Delight view the demonstration page, however, notation this is hosted on a server without PHP and so file uploads will not occur. To exam it, please download the files to examine the lawmaking and host information technology on your own server.
I promise you've enjoyed this serial and are considering how file drag and drop could help your web application.
If you lot enjoyed reading this mail service, you'll love Learnable; the identify to learn fresh skills and techniques from the masters. Members go instant access to all of SitePoint'due south ebooks and interactive online courses, like Learn HTML5.
Source: https://www.sitepoint.com/html5-javascript-file-upload-progress-bar/
0 Response to "Java Script to Show File Upload Progress"
Post a Comment