HTML5 3D Wallpaper by Rafael Otake

Creating Asynchronous File Upload System Using HTML5 File API

Web applications can now ask users to select files and read the content of those files thanks to the File API introduced in HTML5. This tutorial explains how to create an asynchronous file upload system using the File API.

Basics of File API

With File API it’s possible to retrieve the files selected by the users very easily. After selection is done, you can access the files property of file input field which returns a FileList. As the name suggests FileList contains a list of File objects which represent the files selected by the user.
Let’s assume we have a simple file input field. We have also attached an onchange callback to the field which is fired as soon as the user selects some files.


Our showFiles function looks like the following:


function showFiles(){
var files=document.getElementById("upload").files;
console.log("Number Of Files "+files.length);
for(var i=0;i var file=files[i];
console.log("Name: "+file.name+",Size: "+file.size+",Type: "+file.type);
};
};

File object has 3 attributes that can be used to retrieve useful information about a particular file. These are as following:

  • Name: Gives the name of the file which is read-only.
  • Type: Returns the MIME type of the file or "" if no type is determined
  • Size: Returns the total file size.

Showing Thumbnails

Now that we are going to build a file upload system it would be great if we can show the thumbnails of the images that are going to be uploaded to the server. This can be done very easily as following:

function showThumbnails(){

var files=document.getElementById("upload").files;

for(var i=0;i

var file=files[i];

var image=document.createElement("img");

document.getElementById("previewPane").appendChild(image);

var fileReader= new FileReader();

fileReader.onload = (function(img) { return function(e) { img.src = e.target.result; }; })(image);

fileReader.readAsDataURL(file);

}

}

First the above function gets the list of files that are going to be uploaded. document.createElement() function creates an image element. Then we instantiate a FileReader and attach a callback to its onload event. Finally, the readAsDataURL() method reads the content of the file in the background. As soon as the read operation finishes, the src attribute of the image is set as the file content. Then we append the created image element to the previewPane.

Creating Asynchronous Image Upload System

In this section I will show you how to create an asynchronous image upload system using above concepts. As soon as the user selects an image we will show a preview and begin upload process. To notify the user about the upload progress we will use jQuery progressbar widget.

The following is our initial HTML markup:




  

   

   

   

   

   

 

 

  

 



We have included jQuery and jQuery ui library to add support for the progressbar widget. You will admit that the default file upload button does not look very cool! How about creating a custom one? To do so, we have created our own button with a little bit of CSS. If we are creating a new button it does not make any sense to display the default file upload button. So, we hide it and as soon as somebody clicks on our custom button, we programmatically perform a click on the default upload button. The following JavaScript does the above trick:




The progressbar is initially hidden as we want to show the progress as soon as upload starts.

Next, we will retrieve the selected file, show the thumbnail and start upload process in the background. The following code does this task:


function handleFile(files){

  var fileReader=new FileReader();

  var file=files[0];

  var imageElem=document.createElement("img");

  fileReader.onload = (function(img) { return function(e) { img.src = e.target.result; }; })(imageElem);

  fileReader.readAsDataURL(file);

  document.getElementById("images").appendChild(imageElem);

  uploadFile(file);

}

You can easily understand the above code as the concept of showing thumbnails has already been discussed in the previous section. The function uploadFile() does the actual task of uploading. The method looks like following:


function uploadFile(file){

  var xhr = new XMLHttpRequest();

  var formData = new FormData();

  formData.append('file',file);

  xhr.upload.addEventListener("progress", function(e) {

    if (e.lengthComputable) {

        var percentage = Math.round((e.loaded * 100) / e.total);

        $("#progressbar").progressbar("value",percentage);

                $("#percentage").html(percentage+"%");

    }

  }, false);

                 

  xhr.upload.addEventListener("loadstart", function(e){

    $("#progressbar").show();

    $("#percentage").show();

  }, false);

  

  xhr.upload.addEventListener("load", function(e){

    $("#progressbar").progressbar("value",100);

    $("#percentage").html("100% Done");

  }, false);

  xhr.open("POST", "http://extremecss.com/demos/html5-upload/upload.php");

  xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');

  xhr.send(formData);

}

The above function takes a File object as argument. First we create an XMLHttpRequest object for asynchronous upload. The FormData object is an ordered collection of entries. We add our file to the FormData object and give it a name file. The XMLHttpRequest has a property upload which is of type XMLHttpRequestUpload. We attach several callbacks to it. The loadstart callback will be fired as soon as upload starts and here we show our progressbar. The progress callback is registered to give the user feedback about the upload progress. Here we calculate the percentage of the file uploaded and update our progressbar accordingly. Lastly the load callback is fired once the file is uploaded and then we update our progressbar to 100%.

On the server-side the PHP script upload.php handles the file upload. The content of the script is as following:


if(isset($_FILES['file'])) {

    if(move_uploaded_file($_FILES['file']['tmp_name'], "uploads/" . $_FILES['file']['name'])){

                echo "success";

               exit;

    }

}

We open a connection to our PHP script through a call to xhr.open() and a subsequent call to xhr.send() starts the upload process asynchronously.

I have tested the script in Chrome 24 and FireFox 11. However, the script will not work in IE 9 and older versions. The HTML5 file api is a part of IE 10.

Conclusion

HTML5 File API gives developers enormous opportunity to build the next generation web applications that heavily interact with local file system. You can easily extend the above application to support drag and drop and multiple file upload feature. Mozilla Developer Network has a nice tutorial for this.

The following two tabs change content below.
Sandeep is a guy who is passionate about the web. He's in love with Java, JavaScript, and PHP. While not doing programming, he likes to play games on his Note II and iPod. Sandeep is the co-founder of a rapidly developing Tech and Gadgets website GadgeticWorld.

Latest posts by Sandeep Panda (see all)

  • Pingback: Charlie

  • Richard Slack

    Thanks for this, I just made a nice photo gallery upload page based on your code but using foundation framework instead of jquery ui. Dropped the thumbs into a block grid, each with a nice little progress bar. Looks really nice.

    • Prasanna

      @Richard: Please send code, I used jQuery File Upload.

    • Kalyan Vara

      Hey Richard. I am working on similar requirement, Could you please he me in this.

      Could you please share the sample code with me. My email id is vara.kalyan@gmail.com.

  • Prasanna

    Thanks, It’s very useful. I am new to HTML5. I used jQuery File Upload plugin to achieve this.

    • http://www.leprojecteur.com Titos

      I gave up on jQuery File Upload as I could never figure it out to get the plug-in to upload to my own folder. Their documentation is scant and not for beginners.
      Changed the permissions, changed the path in uploadHandler class never worked after a whole day.

  • Pingback: HTML 5 Uploader and What You Need to Know Before Coding - Fresh Web Dev

  • Igor Carvalho de Paula

    Great

  • TonyNhan

    I want setdafault fileToUpload in ( <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" ) as url in mycomputer ex:D:downloadabc.excel ???? can you help me?