How to Implement the upload progress bar based on HTML5 Ajax (jquery version ),
In the previous article, I introduced the background Servlet in this article. So here we only look at the front-end JS Code.
First, HTML5 uses AJAX to submit data. First, we need to learn a newly added HTML5 object: FormData.
The FormData object can use the append method to add key-value data. Unlike json, which we used previously, binary files can be uploaded asynchronously.
1. Create a FormDate object
var formData = new FormData();
2. Add data to the FormDate object
FormData. append ("catname", "I am a meow"); formData. append ("age", 1); // The numeric type is converted to the string type. // The uploaded binary file can be added. For example, the fileInputElement object contains the formData file selected by the user. append ("userfile", fileInputElement. files [0]); // You can also add a Blob Object To formData var oFileBody = "<a id =" a "> <B id =" B "> hey! </B> </a> "; var oBlob = new Blob ([oFileBody], {type:" text/xml "}); formData. append ("webmasterfile", oBlob );
3. Use the FormData object
var xhr = new XMLHttpRequest();xhr.open("POST", "upload");xhr.send(formData);
HTML section
After a brief introduction to the FormData object, let's see how the HTML code of the page is written.
<br/> <input type = "file" id = "pic" name = "pic" onchange = "showPic () "/> <input type =" button "value =" Upload image "onclick =" uploadFile () "/> <br/> <div id =" parent "> <div id =" son "> </div>
The bottom div is used to display the progress bar, so the corresponding css style is required. The style is as follows. The color is not easy to see. Change it by yourself:
<style type="text/css"> #parent{width:550px; height:10px; border:2px solid #09F;} #son {width:0; height:100%; background-color:#09F; text-align:center; line-height:10px; font-size:20px; font-weight:bold;} </style>
JS Section
The most important thing is that after jquery is loaded on the page, we can see how JavaScript is written. The first is the onchange event Method of the file component:
function showPic(){ var pic = $("#pic").get(0).files[0]; $("img").prop("src" , window.URL.createObjectURL(pic) );}
The first line of showPic is to get the uploaded file from the file object. The second line sets the src attribute for img. You can get instant preview on the page.
Before reading the uploadFile method, let's take a simple look at the Progress event (progress Events) Progress ......
The Progress Events specification is a W3C working draft that defines Events related to client server communications. These events are first performed on XHR, but are also used by other APIs for reference. There are the following 6 Progress events.
Loadstart: triggered when the first byte of the corresponding data is received.
Progress: continuously triggered during the receiving period. // Let's just look at one.
Error: triggered when a request error occurs.
Abort: triggered when the link is terminated because the abort () method is called.
Load: triggered when the complete data is received.
Loadend: triggered after communication is completed or an error, abort, or load event is triggered.
The progress event is submitted by Mozilla, which is periodically triggered when the browser receives new data. The onprogress event handler receives an event object whose target attribute is an XHR object, but contains three additional attributes:
LengthComputable: Boolean value indicating whether progress information is available
Position: number of received bytes
TotalSize: The expected number of bytes determined based on the Content-Length header.
With this information, we can create a progress indicator for the user. But the problem arises again. jQuery's ajax method does not have any operations on the progress event. How can this problem be solved ~~
Fortunately, we found that the XMLHttpRequest object called by jQuery's ajax method can be specified !!!
Let's look at Row 3. Therefore, when the ajax part of the uploadFile method is used, the Code becomes this style.
The most important part of the Code:
Function uploadFile () {// obtain the uploaded file and put it in the formData object var pic =$ ("# myhead "). get (0 ). files [0]; var formData = new FormData (); formData. append ("file", pic); $. ajax ({type: "POST", url: "upload", data: formData, // The data uploaded here uses the formData object processData: false, // The correct Content-Type contentType: false is automatically added only when the value is false. // here we get the XMLHttpRequest object generated by jQuery and add the progress event binding for it, then return to ajax and use xhr: function () {var xhr = $. ajaxSettings. xhr (); if (onprogress & xhr. upload) {xhr. upload. addEventListener ("progress", onprogress, false); return xhr ;}}});}
The onprogress method is added to end the entire function.
/*** Detects the attachment upload status. This method is executed every 0.05-0.1 seconds */function onprogress (evt) {var loaded = evt. loaded; // The uploaded size. var tot = evt. total; // total attachment size var per = Math. floor (100 * loaded/tot); // percentage of uploaded files $ ("# son" ).html (per + "% "); $ ("# son" ).css ("width", per + "% ");}
The code of the entire page is attached to facilitate comparison.
<! DOCTYPE html>