HTML5 use Formdata object to display progress bar file Upload "turn" __html

Source: Internet
Author: User
Tags event listener html form

From: http://blog.csdn.net/q1056843325/article/details/53759963

This article is my translation of the foreign language, not my original
Online see a lot of blogs have reproduced this article
But it's all in English.
So I decided to translate it.
(Translation and formatting also cost a lot of effort (~"~) ~zz)
English ability is limited, we can do it (translation has a slight change)
(PS: For the compatibility of the following version of the issue please ignore, after all, this article also counted for some time)
In situ: Portal


HTML5 finally solved the problem of uploading the files while also showing the upload progress.
Today, most Web sites use flash players to achieve this feature
Some websites still use the HTML form tag
(Enctype=multipart/form-data)
However, it requires server-side changes to enable users to display the upload progress

In fact, what we need to do is to hook up to the server's byte stream
The server is receiving a file
So we can know how many bytes have been received
And somehow conveys the message back to the client browser
And it's still the file being uploaded
This is a very good solution (especially for large files)
However, it is rather complex
Because you are basically taking over the entire server-side processing (when you dig into the byte stream) HTML5 upload Files

The XMLHttpRequest object has been extended by the HTML5 specification
In particular, the XMLHttpRequest Level 2 standard (currently the latest version)
The following new features have been included: processing byte streams (such as file, Blob, and Formdata objects during upload/download) upload/download process events cross-domain request anonymous requests (do not send HTTP requests) Timeout request

In this article, we mainly use the first two
In particular upload files to use XMLHttpRequest and to provide users with the upload progress information
Note that this workaround does not require any changes on the server side
At most, it's the level of processing multipart/form-data protocols.
Therefore, the existing server-side logic should remain unchanged
This makes the technology easier to adapt

"Figure 1: File Upload (upload just started)"

"Figure 2: File upload (upload completed)"

The picture above provides the user with the following information: file information
File name File size MIME type progress bar (percent complete) upload speed/upload bandwidth remaining estimated time uploaded byte server-side response (inside orange frame)

The last one doesn't seem to matter, but it's really important in this environment.
Keep in mind that users usually do not submit HTML forms after (PS: Here I think it should be the file upload completed) immediately away from the page
Because we use the XMLHttpRequest upload happened in the background, the page still hasn't changed
If your business process can use it
That will bring a good user experience HTML5 progress Events

Follow the HTML5 Schedule event specification
HTML5 Progress events provide the following related information total-bytes transferred loaded-bytes uploaded lengthcomputable-Specify upload total data size (the total size of the uploaded file is known)

You should notice that we need to use these two messages to figure out all the other information we want to show to the user.
It's a very simple calculation.
But it does involve a lot of extra code, and you need to set up timers

Considering that users should also be able to understand progress information
HTML5 's Progress Event specification also takes note of this requirement
At the same time, it is easy for browser vendors to provide additional information after each increase in progress.
So I suggest that the progress event should be modified as follows: Total-Transferred bytes loaded-bytes uploaded-lengthcomputable-Specifies the total upload size (the total size of the uploaded file is known) transferspeed-transfer speed timeremaining -Remaining time function realization

The first is a very simple HTML form

<! DOCTYPE html> 1-2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19-20 21 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19-20

"Code 1:html"

Note that the <input type= "file" > tag has a onchange event bound to the JS function fileselected ()
This event is triggered each time a user browses to a file on the local system
The fileselected () function is as follows:

function fileselected () {
  var file = document.getElementById (' filetoupload '). Files[0];
  if (file) {
    var fileSize = 0;
    if (File.size > 1024 * 1024) {
      fileSize = (Math.Round (file.size * 1024)). ToString () + ' MB '; 1024 >}else{
      fileSize = (Math.Round (file.size * 100/1024)/MB). toString () + ' KB ';      
    document.getElementById (' FileName '). InnerHTML = ' Name: ' + file.name;
    document.getElementById (' FileSize '). InnerHTML = ' Size: ' + fileSize;
    document.getElementById (' FileType '). InnerHTML = ' Type: ' + file.type;
  }
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 2 3 4 5 6 7 8 9 10 11 12 13-14

The Code 2:fileselected () function

The first line in the function did something you might not have seen or done before.
In fact, once you have a <input type= "file" > Element application
You can access an object called FileList, which is part of the new HTML5 specification.
(Part of the HTML5 File API)
FileList object is a collection of files
More specifically, it's a collection of file objects
The file object has the following properties: Name-filename (contains any path) type-file MIME type (lowercase) size-File byte size

It's getting more and more interesting, isn't it.
We can access this information on the client
In fact, the file API (using the FileReader object) also allows us to access the client file contents (file stream or byte)
In this case we're not going to use FileReader, so I'm not going to use other new objects to break your patience.
We still have a few new objects to discuss.

For you, you can use the information provided by the file object
To prevent users from uploading files larger than a certain size
Or you can use the type attribute to find out what type of file the user is trying to upload and modify
The above JavaScript method is populated with gray text (Figure 1 and figure 2 above)
(Use the File object to get information about the selected files)

The size of the file is byte, so there is a way to convert it to a form that we can understand more easily
(for example, use 15.65MB instead of 15795748864 bytes)
After the user selects the file, it will upload the file by clicking the Upload button.
Here also pay attention to upload button onclick event bound JS function UploadFile ()
The UploadFile () function is as follows:

function UploadFile () {
  var xhr = new XMLHttpRequest ();
  var fd = document.getElementById (' Form1 '). Getformdata ();

  /* Event Monitor
  /Xhr.upload.addEventListener ("Progress", uploadprogress, false);
  Xhr.addeventlistener ("Load", Uploadcomplete, false);
  Xhr.addeventlistener ("Error", uploadfailed, false);
  Xhr.addeventlistener ("Abort", uploadcanceled, false);
  /* The following URL must be changed to the server URL you want to send the file * * *
  xhr.open ("POST", "uploadminimal.aspx");
  Xhr.send (FD);
}
1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 The 12 13

The Code 3:uploadfile () function

In the second line of this function, you will see another object Formdata
We've never seen it, nor used it.
Actually you didn't really see it, but we got a reference to it through a method Getformdata ()
Formdata object is similar to a collection of dictionary (data structure), name/value pairs
Part of the name is the name of the form (defined in HTML)
Part of the value is the value of the field
The part of the value can be a string, a number, or even a file object (see Code 4)

So, when you use the Getformdata () method in the table monotone, you get a reference to the Formdata object (the form's key-value pair collection)
You can use this reference as the information you want to send to the server side
This makes it easy to submit the whole form
Now you can manually create a Formdata instance object to send to the server
or add additional information to the Formdata object before sending

Notes on the Formdata
Note that the Chrome6 support for uploading files using the new API when writing this article
The Getformdate () method does not seem to be supported, but the Formdata object is supported
So a Formdata instance was created manually in code 6
Another way to instantiate a formdata is to pass a reference in a FORM element
Like this var fd = new FormData (document.getElementById (' Form1 '));
The advantage of this constructor is that you can populate the Formdata instance with all forms (you don't have to do it manually)
(similar to the previous Getformdata method for discussing form elements, Firefox supports this method when writing this article)

Code 4 shows you how to create a Formdata instance
Assign any fields and values, including references to the file object (via user <input type= "file" > Selected files)

var fd = new FormData ();
Fd.append ("Author", "Shiv Kumar");
Fd.append ("name", "Html 5 File api/formdata");
Fd.append ("Filetoupload", document.getElementById (' Filetoupload '). Files[0]);
1 2 3 4 1 2 3 4

"Code 4: Create a Formdata instance manually"

Let's go back to code 3 and you'll find that we've subscribed to some events of the XMLHttpRequest object
In particular, pay attention to the first line after the event listener annotation in your code
Xhr.upload.addEventListener ("Progress", uploadprogress, false);
The Progress events we subscribe to are not XMLHttpRequest instances, but on the upload properties of XMLHttpRequest instances

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.