HTML5 application file upload,

Source: Internet
Author: User

HTML5 application file upload,

For a long time, developers have been worried about this. Most of them use flash as a solution to solve this problem, but flash is not a panacea because of the flash version, the cut data problem sometimes becomes a nightmare. Some websites use the form label's enctype = multipart/form-data attribute. However, this attribute requires the server to make special settings to display the progress, which is also complex, complexity means errors are easy. This is not what we want.

Now let's take a look at why Html5 can solve this problem and how good it can be.

Upload files with HTML5

In the HTML5 standard, the XMLHttpRequest object is redefined and called "XMLHttpRequest Level 2". It contains the following five new features:

1. Supports uploading and downloading byte streams, such as files, blob, and form data.

2. Added upload and download progress events.

3. Support for cross-origin requests

4. Allow Anonymous Requests (that is, do not send HTTP Referer)

5. Allowed To Set Request timeout

In this tutorial, we mainly focus on the first and second features, especially the Second-it provides the upload progress we want. Unlike the previous scheme, this scheme does not require the server to make special settings. Therefore, you can try it by looking at the tutorial.

The figure above shows what we can achieve:

1. Display uploaded file information, such as file name, type, and size

2. a progress bar that displays the real progress

3. upload speed

4. Estimation of remaining time

5. uploaded data volume

6. The server returns a response after the upload is complete.

In addition, with XMLHttpRequest, the entire upload process is asynchronous. Therefore, when you upload files, you can still operate other elements in the webpage without waiting for the upload to complete. After the upload is complete, we can get the response sent from the server. Therefore, the entire upload process is quite logical.

HTML5 progress events

A Progress event (Progress Events) is added to HTML5, which provides us with the following information:

1. total-File Size

2. loaded-uploaded size

3. lengthComputable-progress can be calculated

There is not much information, but it is sufficient for calculating the File progress. Of course, there are still many things that are not provided directly, which is very sorry.

HTML

It is not much different from the normal file upload code. However, note that the input tag is associated with a JavaScript function on onchange.

<! DOCTYPE html> 

JavaScript

Once we use input in HTML, we can get a FileList object in JS Code. This object is part of the newly added file API in HTML5. Each FileList object is a collection of file objects, and the file object has the following attributes:

1. name-file name (excluding path)

2. type-MIME type of the file (lower case)

3. size-file size (in bytes)

This is exactly what we need. Of course, there is also a FileReader object in HTML5, but we didn't use it here. Now, with the above three content, we have been able to control the size and type of files uploaded by users, so as to reduce the pressure on the server for re-detection and improve the security factor.

 function fileSelected() {  var file = document.getElementById('fileToUpload').files[0];  if (file) {    var fileSize = 0;    if (file.size > 1024 * 1024)      fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';    else      fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';    document.getElementById('fileName').innerHTML = 'Name: ' + file.name;    document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;    document.getElementById('fileType').innerHTML = 'Type: ' + file.type;  }}

So what will happen after you select a file and Click Upload?

 function uploadFile() {  var xhr = new XMLHttpRequest();  var fd = document.getElementById('form1').getFormData();  /* event listners */  xhr.upload.addEventListener("progress", uploadProgress, false);  xhr.addEventListener("load", uploadComplete, false);  xhr.addEventListener("error", uploadFailed, false);  xhr.addEventListener("abort", uploadCanceled, false);  /* Be sure to change the url below to the url of your upload server side script */  xhr.open("POST", "upload.php");  xhr.send(fd);}function uploadProgress(evt) {  if (evt.lengthComputable) {    var percentComplete = Math.round(evt.loaded * 100 / evt.total);    document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';  }  else {    document.getElementById('progressNumber').innerHTML = 'unable to compute';  }}function uploadComplete(evt) {  /* This event is raised when the server send back a response */  alert(evt.target.responseText);}function uploadFailed(evt) {  alert("There was an error attempting to upload the file.");}function uploadCanceled(evt) {  alert("The upload has been canceled by the user or the browser dropped the connection.");}

In the second line of the Code, our JS Code uses FormData, a new HTML5 object. The FormData object is a collection of user form data. It stores form data in the form of key-value pairs. Its values can include numbers, strings, and files. We submit data to the server by moving this object.

Of course, we can also build this object manually in the Code, such as the following:

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]);

Return to the topic. Looking back at the previous code, we added a lot of event listening for XMLHttpRequest to get the real situation of file upload. In particular, what we hook is not XMLHttpRequest itself, but its attributes, such as uploadProgress.

Complete code

Finally, let's take a look at the complete code.

 <!DOCTYPE html>

Have our tasks been completed? It can be said that this code has been able to complete the task of uploading files and display the upload progress. But we should say we do not, because apart from this skeleton HTML, there are still many things we have not done, such as CSS beautification. However, this is not the topic of our article.

Finally, let me remind you that the code of the tutorial should run on a browser that supports new features. If you do not know whether your browser supports the code, you can query it here.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.