Based on HTML5 Ajax file upload progress bar How to implement (jquery version) _ajax related

Source: Internet
Author: User
Tags file upload file upload progress bar

In the last article to introduce you to this article inside the background servlet. So here only look at the front desk JS code.

First HTML5 to use AJAX to submit data first to learn a HTML5 new object: FormData

The FormData object can be added using the Append method for Key-value data, unlike the JSON we used to use to upload binary files asynchronously.

1, the creation of Formdate objects

var formData = new FormData ();

2, add data to the Formdate object

Formdata.append ("CatName", "I am a Meow");
Formdata.append ("Age", 1); The number type is converted to a string type
//can increase the uploaded binaries, such as the Fileinputelement object already contains the user's selected file
formdata.append ("UserFile", Fileinputelement.files[0]);
You can also add a Blob object to the 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 FormData Object

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

HTML section

After a simple introduction to the FormData object, let's look at how the HTML code for the page is written.

<br/> <input type= " 
file" id= "pic" name= "pic" onchange= "showpic ()"/ >
<input type= "button" value= "Upload picture" onclick= "UploadFile ()"/><br/> <div id= 
"Parent" >
 <div id= "son" ></div>
</div>

The bottom div is used to display the progress bar, so you need the corresponding CSS style. The style is as follows, the color is not good-looking, own change:

<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, and after we load jquery on the page, let's see how JavaScript is written, first of all, the OnChange event method for 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 results on a page.

Before we look at the UploadFile method, let's simply learn the Progress of the Progress event (Progress events) ...

The Progress events specification is a working draft of the consortium that defines the event associated with Client server communication. These events were originally intended for XHR operations, but are now being referenced by other APIs as well. There are 6 progress events in the following.

Loadstart: Triggered when the first byte of the corresponding data is received.
Progress: constant triggering during receiving the corresponding period. We'll just look at one.
Error: Triggered when an error occurs on the request.
Abort: Triggered when a link is terminated because of a call to the Abort () method.
Load: Triggers when a complete corresponding data is received.
Loadend: Triggered after communication completes or triggers an error, abort, or Load event.

The progress event was submitted by Mozilla and is periodically triggered when the browser receives new data. The OnProgress event handler receives an event object whose target property is a Xhr object, but contains three additional attributes:

Lengthcomputable: Boolean value indicating whether progress information is available

Position: Indicates the number of bytes that have been received

TotalSize: Represents the expected number of bytes determined according to the content-length corresponding header.

With this information, we can create a progress indicator for the user. But here's the problem, jquery's AJAX approach has no action on progress events. How to play this ~ ~

Fortunately, the XMLHttpRequest object of the Ajax method invocation of jquery is the one that can be specified by looking at the data!!!

Look at the 8453 line, that's it. So the code becomes this style when the Ajax part of the UploadFile method is used.

The most important part of the code:

function UploadFile () {
//Get upload file, put into Formdata object
var pic = $ ("#myhead"). Got (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
PROCESSDA Ta:false, 
//must be false to automatically add the correct content-type 
contenttype:false,//
Here we'll get the XMLHT from jquery.      Tprequest object, add progress event bindings to it, and then return to Ajax using
xhr:function () {
var xhr = $.ajaxsettings.xhr ();
if (onprogress && xhr.upload) {
Xhr.upload.addEventListener ("Progress", onprogress, false);
return XHR;
}
} 
);
    

Finally, add the OnProgress method, to the entire function to spend a period.

/**
 * Detection attachment upload situation, this method about 0.05-0.1 seconds to perform
 a
/function onprogress (evt) {
var loaded = evt.loaded;     Already uploaded size situation 
 var tot = evt.total;      Total size of the attachment 
 var per = Math.floor (100*loaded/tot);  The percentage already uploaded 
$ ("#son"). html (per + "%");
 $ ("#son"). CSS ("width", per + "%");

Finally, attach the entire page code to facilitate comparison.

<! DOCTYPE html>  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.