Saturday, March 9, 2013

Uploading Files with HTML5 File API and XMLHttpRequest(XHR)

Go to >> Java Tutorials

Target audience: Beginners, Intermediate

I have been developing a file upload component using HTML5 File API , XMLHttpRequest(XHR) and JSF. I would like to share here only the client side part.

The Upload component is

  1. Able to select multiple files of any format. 
  2. Able to keep previously select files, meaning that it should be able to let the user select files one by one and then he should be able to upload whole files later. 
  3. Able to show/restrict/validate selected files from client side (Using HTML5 and JavaScript APIs). Here, I just only show the file size, you can modify this code to validate the file size. 
  4. Able to show the upload progress. Here, I just show the percentage. You can modify the code to make is as a progress bar 
This is how it would look like


I break the major parts of the implementation bellow

  1. When a user selects file or files, the prepare(); method will be called. Its set be invoked while onchange event on the file input element is fired. This prepare() method will show the selected file/files. It creates a table and populates it with files selections. The table has three(3) columns. First column is to show the file name and to keep a hidden image. The hidden img(img.file) element is used to hold the file selections. Second column is to show the file size. The third column is show the progress. 
  2. When the user clicks the upload button after he makes the file selections, the submitUpload() method will be called. Its set be invoked while click event on the submit button element is fired. It grabs all files from the hidden images (img.file) and then create XHR request for each files. The XHR’s events are used to update the progress of the file uploads.

The code is shown bellow.


HTML 5 XHR ( XMLRequestObject) mutiple file upload





2 comments:

  1. to which folder the file will?

    ReplyDelete
  2. Alex, the file will be saved by the server/server side application. its up to the server side implementation.I just shared here only the client part. In my application, i use apache commons ServletFileUpload to parse multipart request and save the file in my preferred location.

    ReplyDelete