HTML5 File Upload with Progress

Source: Internet
Author: User
Tags html form http file upload
HTML5 finally solves an age problem of being able to upload files while also showing the upload. Today most websites with Flash Player to achieve this functionality. Some websites continue to use the html  <form> with Enctype=multipart/form-data,  but and modification on The server side to enable showing users the upload progress. Essentially, what you need to do are hook into the server's byte stream while it's receiving a file so you know how many b Ytes you ' ve received and somehow convey this information back to the client browser, while it's still in the process of U Ploading the file. This solution works extremely-OK and is isn't fraught with the issues Flash Player causes (especially for large files). However it is fairly complicated and not for the faint of heart because your are essentially taking over the entire server Side processing (when you tap into the byte stream) and that includes implementing the  Multipart/form-data  pro Tocol on THe server side and along with a bunch of the other things. uploading files using HTML5The XMLHttpRequest object has gotten a facelift in the HTML5 specifications. Specifically the XMLHttpRequest Level 2 specification (currently the latest version) that has included the following new Features:handling of byte streams such as File, Blob and FormData objects for uploading and downloading Progress events D Uring uploading and downloading Cross-origin requests Allow making anonymous request-that is not send HTTP Referer the A Bility to set a Timeout for the Request

In this post we'll look over closely at #1 and #2. In particular, uploading of the files using XMLHttpRequest and providing upload progress to the information. This is the solution does not require the no change to the server side, at least insofar as handling the Multipar T/form-data protocol. So existing server side logic should remain unchanged, which makes adapting the this technology is much easier.

Figure 1:showing The File Upload screen-upload just started

Figure 2:showing The File Upload screen with Upload completed.Notice in the images above the following pieces of information made available to the the "file that Ha" s been selected such as file Name file Size Mime Type A Progress Bar with percent complete the upload speed or upload band Width The approximate time remaining the bytes uploaded thus far A response from the server side (the Organge box) Item #6 Above may isn't sound important, but in fact are quite important in this context because, remember that the user is not Navi Gating away from this page as she normally would after submitting an HTML form. Because we ' re using XMLHttpRequest, the uploading is happening in the background. The page the user is on remains intact. Which is a nice feature to have if your business process can work with it.Html5 Progress EventAs per of the HTML5 Progress Events spec, the HTML5 Progress event provides the following information to this relevant Ersation total-total bytes being transferred loaded-bytes uploaded thus far lengthcomputable-specifies if the total The size of the Data/file being uploaded is known for you should notice so we need to use this two pieces of information to Cal Culate (figure out) the "Other" information we ' re displaying to the user. It is fairly-figure out all of the the other information given the above two pieces of information but it does ve quite a bit of extra coding and setting up a timer.HTML5 Progress Event-what It should have beenConsidering that those who go down the route of providing upload progress information to the end user would require to show All of the "other information" to "End user as", "HTML5 Progress Event specifications should have for T His need as as a, as it would is fairly simple for browser vendors to provide this additional pieces of information each Time the progress event is raised. So I propose the progress event should is modified to the Following:total-total bytes being transferred Ytes uploaded thus far lengthcomputable-specifies if the total size of the Data/file being uploaded is known Transferspe Ed as a long timeremaining as a JavaScript Date objectHtml5 Upload using XMLHttpRequestI ' ve provided a uploading files using HTML5 with Progress indication Demo-for-those who want to jump right to it. All of the JavaScript code required are in the page. However, because the demo is a real world demo there are a number of CSS styles in, and the layout of the page (the Ht ML) is fairly complex. In this article we work with a minimalistic version of the Html and JavaScript so-keep things simple and Understanda ble.Browser Support for this FeatureAt the "time" of this writing only the following browsers support this feature Firefox 4.0 Beta 6 Chrome 6 Safari 5.02 IE 9 Beta and Opera 10.62 don't support this featureLet ' s get startedThe entire code listing for the minimalistic but functional implementation the can is found in code listing 6. Each aspect of the "minimalistic html/javascript is explained into detail in the rest of" this article. Below, is a very simple Html form. This HTML is no different then the HTML with the ' d use to do a regular html/http file upload your ' d use today (HTML4 and pretty Much any previous version of Html).The Html portion

<! DOCTYPE html>
Code Listing 1:the bare minimum Html PageNotice that the <input type= "file"/> element has the onchangeEvent assigned to a JavaScript method called fileselected (). So essentially, the someone selects a file by browsing to a file in their local system, the This event is raised. The fileselected ()JavaScript method looks like the following. The fileselected () JavaScript method
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 * 1024)). ToString () + ' MB ';
    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;
  }
}
Code Listing 2:the fileselected () JavaScript methodThe "the" The code in the "is doing something" you "ve not seen or done before. Essentially, once you have a reference to the <input type= ' file '/> element, you are have access to what is called a filelistObject which is new in HTML5 and are part of the File API specifications of Html 5. A FileList object is a collection of files. More specifically, it is a collection of FileObjects. A File object has the following properties. Name-the Name of the file (excluding any path) Type-the MIME type of the file (in lower case) size-the size of the F Ile in bytes This is already getting interesting isn ' t it? We have access to this information on the client side! In fact the file API gives us access to the contents of the file (the file stream or bytes) on the client side too, using The FileReader  object. We won ' t be dealing with the  filereader  in-I-example, so I ' m not going to overwhelm for your with yet another NE W object. We have a couple of the new objects to discuss yet. You are could use the information the  File  object provides your to say, prevent users from uploading files larger t Han the certain size. Or you could use the

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.