Home  >  Article  >  Web Front-end  >  jquery+HTML5+Ajax implements file upload function with progress bar

jquery+HTML5+Ajax implements file upload function with progress bar

php中世界最好的语言
php中世界最好的语言Original
2018-04-23 14:53:311731browse

This time I will bring you jquery HTML5 Ajax to implement the file upload function with a progress bar. What are the precautions for jquery HTML5 Ajax to implement the file upload function with a progress bar. , the following is a practical case, let’s take a look.

First of all, HTML5 uses AJAX to submit data. First, you need to learn a newly added object in HTML5: FormData

The FormData object can use the append method to add key-value data, which is different from the json we commonly used before. What is possible is that binary files can be uploaded asynchronously.

1. Creation of FormDate object

var formData = new FormData();

2. Adding data to FormDate object

formData.append("catname", "我是一只喵");
formData.append("age", 1);         // 数字类型会转为字符串类型
// 可以增加上传的二进制文件,比如fileInputElement对象中已经包含了用户所选择的文件
formData.append("userfile", fileInputElement.files[0]);
//也可以将一个 Blob 对象添加到 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. Using the FormData object

var xhr = new XMLHttpRequest();
xhr.open("POST", "upload");
xhr.send(formData);

HTML part

After the brief introduction of 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" id="pic" name="pic" onchange="showPic()"/>
<input type="button" value="上传图片" onclick="uploadFile()" /><br /> 
<p id="parent">
 <p id="son"></p>
</p>
The p at the bottom is used to display the progress bar, so the corresponding css style is required. The style is as follows, the color is not good-looking, 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

The highlight is here, after loading jquery on the page, let’s see how to write JavaScript 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 an instant preview of the effect on the page.

Before looking at the uploadFile method, let us briefly learn about the progress of progress events (Progress Events)...

The Progress Events specification is a working draft of the W3C, defined Events related to client-server communication. These events were originally targeted at XHR operations, but are now also used by other APIs. There are the following 6 progress events.

loadstart: Triggered when the first byte of corresponding data is received.

progress: Triggered continuously during the period of receiving the corresponding response.​ // Let’s just look at one
error: Triggered when an error occurs in the request.
abort: Triggered when the link is terminated due to calling the abort() method.
load: Triggered when complete corresponding data is received.
Loadend: Triggered after communication is completed or error, abort or load event is triggered.

The progress event is submitted by Mozilla. This event will be triggered periodically while the browser receives new data. The onprogress

Event processing program will receive an event object, whose target attribute is an XHR object, but contains three additional attributes:

lengthComputable: a Boolean value indicating whether progress information is available

position: Indicates the number of bytes that have been received

totalSize: Indicates the expected number of bytes determined based on the corresponding Content-Length header.

With this information, we can create a progress indicator for the user. But the problem comes again, jQuery's ajax method has no operations on the progress event. How to play this~~

Fortunately, after consulting the information, I found that the XMLHttpRequest object called by jQuery's ajax method can be specified! ! !

Look at line 8453, that’s it. So the code becomes this style in the ajax part of the uploadFile method.

The most important part of the code:

function uploadFile(){
  
  // 获取上传文件,放到 formData对象里面
  var pic = $("#myhead").get(0).files[0];
  var formData = new FormData();
 formData.append("file" , pic);
  $.ajax({
    type: "POST",
    url: "upload",
    data: formData ,  //这里上传的数据使用了formData 对象
    processData : false, 
    //必须false才会自动加上正确的Content-Type 
    contentType : false , 
    
    //这里我们先拿到jQuery产生的 XMLHttpRequest对象,为其增加 progress 事件绑定,然后再返回交给ajax使用
    xhr: function(){
      var xhr = $.ajaxSettings.xhr();
      if(onprogress && xhr.upload) {
        xhr.upload.addEventListener("progress" , onprogress, false);
        return xhr;
      }
    } 
  });
}
Finally add the onprogress method to bring the entire function to an end.

/**
 * 侦查附件上传情况 ,这个方法大概0.05-0.1秒执行一次
 */
function onprogress(evt){
  var loaded = evt.loaded;     //已经上传大小情况 
 var tot = evt.total;      //附件总大小 
 var per = Math.floor(100*loaded/tot);  //已经上传的百分比 
  $("#son").html( per +"%" );
 $("#son").css("width" , per +"%");
}
Finally, the code of the entire page is attached for easy 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);
  /** 
   * 必须false才会避开jQuery对 formdata 的默认处理 
   * XMLHttpRequest会对 formdata 进行正确的处理 
   */ 
  $.ajax({
   type: "POST",
   url: "upload",
   data: formData ,
   processData : false, 
   //必须false才会自动加上正确的Content-Type 
   contentType : false , 
   xhr: function(){
    var xhr = $.ajaxSettings.xhr();
    if(onprogress && xhr.upload) {
     xhr.upload.addEventListener("progress" , onprogress, false);
     return xhr;
    }
   } 
  });
 }
 /**
  * 侦查附件上传情况 ,这个方法大概0.05-0.1秒执行一次
  */
 function onprogress(evt){
  var loaded = evt.loaded;     //已经上传大小情况 
  var tot = evt.total;      //附件总大小 
  var per = Math.floor(100*loaded/tot);  //已经上传的百分比 
  $("#son").html( per +"%" );
  $("#son").css("width" , per +"%");
 }
 </script>
 </head>
 <body>
 <img width="400" height="250"/><br /> 
 <input type="file" id="pic" name="pic" onchange="showPic()"/>
 <input type="button" value="上传图片" onclick="uploadFile()" /><br /> 
 <p id="parent">
  <p id="son"></p>
 </p> 
 </body>
</html>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Jquery LigerUI detailed explanation of file upload steps

jquery dynamically loaded js file detailed explanation

How to read XML file content with jQuery

The above is the detailed content of jquery+HTML5+Ajax implements file upload function with progress bar. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn