HTML5 some uses of the upload API (on)

Source: Internet
Author: User
Tags http redirect

HTML5提供了很多有用的API,其中就包括上传的API,XMLHttpRequest2.0,在HTML5时代之前,需要进行二进制的上传一般都会才用flash的方案,但是当XMLHttpRequest2.0出来之后,完全可以使用HTML5的上传解决方案,能够非常方便的进行二进制上传进度的显示,上传图片的本地预览,甚至可以做到断点续传,分片上传,多文件上传等各种复杂的底层功能。  

First of all, review the transmission process of XMLHttpRequest1.0

About XMLHttpRequest initializing XMLHttpRequest

?? To transfer files using XMLHttpRequest, first we have to create a XMLHttpRequest object, and each time a xmlhttprequest is created, this property is generated readystate when a XMLHttpRequest Initial creation, the value of this property starts at 0, until the full HTTP response is received, and this value is increased to 4. Each of the 5 states has an associated informal name, and the following table lists the status, name, and meaning:

State Name Describe
0 Uninitialized Initializes the state. The XMLHttpRequest object has been created or has been reset by the Abort () method.
1 Open The open () method was called, but the Send () method was not called. The request has not been sent yet.
2 Sent????? The Send () method has been called and the HTTP request has been sent to the WEB server. The response was not received.
3 Receiving All the response headers have been received. The response body begins to receive but is not completed.
4 Loaded The HTTP response has been fully received.

?????

var New // readystate is 0

Xhr.open method Setting Initial parameters

?? Then we need to initialize some parameters of the HTTP request, but this is just the initialization, which means setting some parameters for uploading, but not uploading them.

// readystate is 1

The method parameter is the HTTP methods used for the request. Values include GET, POST, and HEAD.

The URL parameter is the principal of the request. Most browsers implement a homogenous security policy and require the URL to have the same host name and port as the text containing the script.

The async parameter indicates that the request use should be performed asynchronously. If this parameter is false, the request is synchronous, and subsequent calls to send () will be blocked until the response is fully received. If this parameter is TRUE or omitted, the request is asynchronous and typically requires a onreadystatechange event handle.

The username and password parameters are optional and provide certification for the authorization required for the URL. If specified, they overwrite any qualifications specified by the URL itself.

The Xhr.send () method sends the request

?? After the parameters of the HTTP request are set, they can be sent.

// readystate is 2

?? Xhr.send () causes an HTTP request. If you have not previously called open () or readyState is not 1,xhr.send () you will run an error. Otherwise, it sends an HTTP request that consists of the following parts: The HTTP method, URL, and authentication qualification (if any) that was specified before Xhr.open () was called. The requested header (if any) that was specified before calling Xhr.setrequestheader (). The body parameter passed to this method.

?? After the request is published, send () sets ReadyState to 2 and triggers the onreadystatechange event.

About the onReadyStateChange event

?? onReadyStateChange is actually the parameter that will be triggered whenever the readystate changes, which means we can judge the value of readystate directly in the onReadyStateChange event. If ReadyState equals 4, it can execute the callback method after the upload is complete.

?? If the Xhr.open () parameter previously called Async is False, this method blocks and does not return until the ReadyState is 4 and the server's response is fully received. Otherwise, if the async parameter is true, or if the parameter is omitted, Xhr.send () returns immediately. If the server responds with an HTTP redirect, the Xhr.send () method or the background thread automatically follows the redirect. When all HTTP response headers have been received, the xhr.send () or background thread sets ReadyState to 3 and triggers the onreadystatechange event handle. If the response is longer, the xhr.send () or background thread may trigger the onReadyStateChange event handle in State 3: This can be used as a download progress indicator. Finally, when the response is complete, the xhr.send () or background thread sets ReadyState to 4 and the last time the event handle is triggered.

With the above initialization, open,send, which has monitored the return value of the onReadyStateChange event to trigger the callback method, we have completed an AJAX request.

About XMLHttpRequest2.0

?? The new features that add XMLHttpRequest2.0 to HTML5 include the following:

    • You can set the time limit for HTTP requests.
    • You can use the Formdata object to manage form data.
    • can upload files.
    • You can request data under different domain names (cross-domain requests).
    • You can get binary data on the server side.
    • The progress information for the data transfer can be obtained.

Here we mainly say and upload files are closely related to the section

About Formdata

?? Ajax is usually used for the submission of mock-up forms, that is to say, XMLHttpRequest1.0 data is often used in the non-flush submission, in order to facilitate the processing of forms, HTML has a new Formdata object that can be used to simulate the form. Use the following:

var formdata=New  formData ();  Formdata.append (' name ', "Jack");  Formdata.append (' uid ', 666666);  

?? The above three lines of code are implemented to insert two fields into a formdata () object, a name, a UID and then we can commit Ajax as if it were XMLHttpRequest1.0:

var xhr=New  XMLHttpRequest ();  Xhr.open ("post", URL);  Xhr.send (formData);  

About HTML5 multiple file uploads

?? So how do we actually want to solve the process of uploading files with HTML5? <input type="file"/>A new file object is added to the tag in HTML5, and the ability to add multiple files can be implemented by setting the multiple property on the input tag, while the files are actually an array object, and the file is all that is in this file tag;
?? Then we want to upload the file is very simple, the direct loop files object gets the files that the user added to the file control and all through the Formdata object's Append method to add to Formdata, and then send.

var formdata=New  formData ();    for (var i=0;i<files.length;i++) {      formdata.append (i,files[i]);} var xhr=New  XMLHttpRequest ();  Xhr.open ("post", URL);  Xhr.send (formData);  

Through the above code can be implemented for multi-file upload.

About the various requirements in HTML5 upload

Although the above implementation of the upload for a number of files, but everyone in the actual work for the upload of the demand is certainly not only can upload, below we say the use of HTML5 for the upload API in the new addition of a lot of useful things can achieve the effect;

Local preview prior to uploading

?? Everyone in the file upload, often encounter need to preview file size, file name and other information, about these HTML5 has helped us encapsulate the corresponding API, we just need to invoke the method can be said about the <input type="file" /> tag has a files array object, In fact, each value in this array object has some corresponding properties that can be called

    • name– file name (no path included)
    • MIME type of type– file (lowercase)
    • Size of the size– file (in bytes)

By calling the above three properties, you can get some information about each file locally, and the method is as follows

functionfileselected () {varFile = document.getElementById (' filetoupload '). Files[0];//get to upload control object files    if(file) {varFileSize = 0; if(File.size > 1024 * 1024) {fileSize= (Math.Round (file.size */(1024x768)/+). ToString () + ' MB '; }Else{fileSize= (Math.Round (file.size * 100/1024)/+). ToString () + ' KB '; } document.getElementById (' FileName '). InnerHTML = ' Name: ' +File.name; document.getElementById (' FileSize '). InnerHTML = ' Size: ' +fileSize; document.getElementById (' FileType '). InnerHTML = ' Type: ' +File.type; }}

About FileReader

?? About the local preview, some files related information we can already get, but if I want to upload a picture, want to directly local preview this image can be directly completed in the local? The answer is yes, you just have to master the FileReader object.

?? There are 4 methods in the FileReader object, 3 of which can read the file and the other to interrupt the read. The method does not return a read result, regardless of the success or failure of the read, which is stored in the result property. The 4 methods were:

    • readasbinarystring (file)????? To read a file as a binary encoding
    • Readastext (file,[encoding])??? To read a file as text
    • Readasdataurl (file)??????? Read the file as Dataurl
    • Abort???????????? Interrupt read operation

FileReader objects also have many events, namely:

    • Onabort???? Interrupt
    • OnError???? Error
    • Onloadstart?? Begin
    • OnProgress?? is reading
    • OnLoad???? Successfully read
    • Onloadend?? Read complete regardless of successful failure

Then we can implement the relevant method of local preview image based on the above event method:

var New FileReader ();  // Create a FileReader object   Reader.readasdataurl (file);      // The file is read into the page as a data URL, and the result exists in  the results property reader.onload=function(e) {      // when the file has been  successfully read    var imgbox= document.getElementById ("Imgbox");          imgbox.innerhtmlthis. Result + '  /> ';  // Show Files   }  

The above method can realize the local preview of the picture, of course, the above method can also be combined with the previous files object Type,size and other properties to achieve the upload image type size limit.

About the HTML5 upload part, there are actually a lot of application places, will be in the future blog to tell you.

HTML5 some uses of the upload API (on)

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.