How to implement the upload progress bar of Ajax file based on HTML5 (jQuery version)

Time:2020-11-23

In the last article, I introduced it to youThe background servlet in this article。 So we only look at the JS code in the foreground.

First of all, HTML5 uses Ajax to submit data. First, learn a new HTML5 object: formdata

Formdata objects can use the append method to add key – value data. Different from the previous JSON, we can upload binary files asynchronously.

1. Creation of formdate object


var formData = new FormData();

2. Add data to the formdate object

formData.append "Catname", "I am a meow");
formData.append ("age", 1); // numeric type will be converted to string type
//You can add uploaded binary files. For example, the fileinputelement object already contains the file selected by the user
formData.append("userfile", fileInputElement.files[0]);
//You can also add a blob object to formdata
var oFileBody = "<a><b>hey!</b></a>"; 
var oBlob = new Blob([oFileBody], { type: "text/xml"});
formData.append("webmasterfile", oBlob);

3. Using 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 take a look at how the HTML code of the page is written

<img width="400" height="250"/><br /> 
<input type="file" name="pic" onchange="showPic()"/>
< input type = "button" value = upload image "onclick =" uploadfile() "/ > < br / > 
<div>
 <div></div>
</div>

The bottom div is used to display the progress bar, so you need the corresponding CSS style. The style is as follows. If the color is not good, please change it 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 part

Here’s the play. After loading jQuery on the page, let’s see how JavaScript is written. First, 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 in the page.

Before looking at the UploadFile method, let’s briefly learn the progress of progress events

The progress events specification is a working draft of W3C, which defines the events related to client server communication. These events were originally used for XHR operations, but they are also used for reference by other APIs. There are six progress events.

Loadstart: triggered when the first byte of the corresponding data is received.
Progress: continuously triggered during the corresponding period of receiving. / / let’s just watch one
Error: triggered when an error occurs in the request.
Abort: triggered when the link is terminated because the abort() method is called.
Load: triggered when the complete corresponding data is received.
Loaded: triggered after communication is completed or after an error, abort, or load event is triggered.

The progress event is submitted by Mozilla and is triggered periodically during the browser’s reception of new data. The onprogress event handler receives an event object whose target attribute is XHR object, but contains three additional attributes:

Lengthcomputable: Boolean value indicating whether progress information is available

Position: indicates the number of bytes received

Totalsize: indicates the expected number of bytes determined according to the corresponding content length header.

With this information, we can create a progress indicator for the user. But again, jQuery’s Ajax method does not operate on the progress event. How do you play this~~

Fortunately, we can find that the XMLHttpRequest object called by jQuery’s Ajax method can be specified!!!

Look at line 8453. That’s it. So the Ajax part of the UploadFile method changes to this style.

The most important part of the code:

function uploadFile(){
  
  //Get 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, 
    //You must false to automatically add the correct content type 
    contentType : false , 
    
    //Here, we first get the XMLHttpRequest object generated by jQuery, add the progress event binding for it, and then return it to Ajax for use
    xhr: function(){
      var xhr = $.ajaxSettings.xhr();
      if(onprogress && xhr.upload) {
        xhr.upload.addEventListener("progress" , onprogress, false);
        return xhr;
      }
    } 
  });
}

Finally, the onprogress method is added to make a full stop for the whole function.

/**
 *This method is about 0.05-0.1seconds
 */
function onprogress(evt){
  var loaded =  evt.loaded ; // uploaded size 
 var tot =  evt.total ; // total size of attachments 
 var per =  Math.floor (100 * loaded / TOT); // percentage of uploaded 
  $("#son").html( per +"%" );
 $("#son").css("width" , per +"%");
}

Finally, the code of the whole page is attached for comparison.

<!DOCTYPE html>
<html>
 <head>
 <title>html5_2.html</title>
 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 <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>
 <script type="text/javascript" src="js/jquery-1.9.1.js"></script>
 <script type="text/javascript">
 function showPic(){
  var pic = $("#pic").get(0).files[0];
  $("img").prop("src" , window.URL.createObjectURL(pic) );
  uploadFile();
 }
 function uploadFile(){
  var pic = $("#pic").get(0).files[0];
  var formData = new FormData();
  formData.append("file" , pic);
  /** 
   *Must be false to avoid jQuery's default processing of formdata 
   *XMLHttpRequest handles formdata correctly 
   */ 
  $.ajax({
   type: "POST",
   url: "upload",
   data: formData ,
   processData : false, 
   //You must false to automatically add the correct content type 
   contentType : false , 
   xhr: function(){
    var xhr = $.ajaxSettings.xhr();
    if(onprogress && xhr.upload) {
     xhr.upload.addEventListener("progress" , onprogress, false);
     return xhr;
    }
   } 
  });
 }
 /**
  *This method is about 0.05-0.1seconds
  */
 function onprogress(evt){
  var loaded =  evt.loaded ; // uploaded size 
  var tot =  evt.total ; // total size of attachments 
  var per =  Math.floor (100 * loaded / TOT); // percentage of uploaded 
  $("#son").html( per +"%" );
  $("#son").css("width" , per +"%");
 }
 </script>
 </head>
 <body>
 <img width="400" height="250"/><br /> 
 <input type="file" name="pic" onchange="showPic()"/>
 < input type = "button" value = upload image "onclick =" uploadfile() "/ > < br / > 
 <div>
  <div></div>
 </div> 
 </body>
</html>