Creating a File Uploader Using JavaScript and HTML 5

Introduction

 
This article explains how to upload a file using HTML 5 and JavaScript. HTML 5 provides an input type "File" that allows us to interact with local files. The File input type can be very useful for taking some sample files from the user and then doing some operation on that file. We will be using the File API in our project, so if you need any detailed description of any function then you can check that API. It also contains various other methods to deal with binary files. The interfaces we will use are the FileList interface to get the list of files, File Reader interface for reading the file, File Interface to get file attributes and so on.
 

Checking the support

 
Since HTML 5 is quite new and not all of its features are supported by all browsers, it's better to check whether your browser supports the file features or not. To check this, just put this piece of snippet in your HTML file and check if you get an alert.
  1.  <script>  
  2.     if (window.File && window.FileReader && window.FileList && window.Blob) {  
  3.         alert("File API supported.!");  
  4.     } else {  
  5.         alert('The File APIs are not fully supported in this browser.');  
  6.     }  
  7.    
  8. </script> 
If you are getting the message as shown in the following picture then you can proceed in this article otherwise you need to update your browser.
 
a8p1.PNG.jpg
 

File input tag

 
The File input tag is the same as other input tags of HTML but the only difference is "type". For file type input we need to set the input type of an element to "file" type. Just as in the following code snippet:
 
a8p2.JPG
 

Selecting the file

 
To select a file, just click on the "Choose file" button of your HTML page and select a file from open dialog. If you have enabled multiple selections then you can select the multiple files. Check the following picture for reference.
 
a8p3.JPG
 
a8p4.JPG
 

Processing the selected file

 
Now we have the file selected by the user. Next, we will check the properties of that file. For that, we will use the File interface. The File interface has two important attributes that are quite useful for us. They are:
  1. readonly attribute DOMString name;  
  2. readonly attribute Date lastModifiedDate;  
As the name of the attributesindicate, the first one provides the name of the file and the second provides the last modified date.
 
To use this interface in our JavaScript (from now onwards I'll use script only) code just use the following code snippet.
  1. function startRead(evt) {  
  2.     var file = document.getElementById('file').files[0];  
  3.     if (file) {  
  4.         //  getAsText(file);  
  5.         alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);  
  6.     }  
Now in your HTML input tag add an onchange event and call this function as in the following:
  1. <input type=file id='file' onchange="startRead()"/> 
If you have done everything right so far then you will get an output similar to this picture.
 
a8p5.JPG
 

Adding drag and drop

 
So far we are selecting the file by the use of the button but to make it more user friendly let us add a drag and drop support so that the user can drag the file on the div to open it., To make this functionality alive just add the following script in your script section.
  1. function startReadFromDrag(evt) {  
  2.         var file = evt.dataTransfer.files[0];  
  3.         if (file) {  
  4.             //  getAsText(file);  
  5.             var fileAttr = "Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate;  
  6.             $('#draghere').text(fileAttr);  
  7.             alert(fileAttr);  
  8.        
  9.         }  
  10.         evt.stopPropagation();  
  11.         evt.preventDefault();  
  12.     }  
  13. var dropingDiv = document.getElementById('draghere');  
  14. dropingDiv.addEventListener('dragover', domagic, false);  
  15. dropingDiv.addEventListener('drop', startReadFromDrag, false); 
And also add this HTML and style code for better output:
  1. <div id="draghere" >Drop files here</div>  
  2.   
  3. #draghere{  
  4.   width:300px;  
  5.   height:100px;  
  6.   background-color:rgba(221,214,155,0.4);  
  7.   border:1px dashed black;  
  8.   text-align:center;  
The code is simple. The HTML line basically provides a div for which the user can drag the file to begin the upload. In the script, what we have done in lines 13-15 is just grab the element and then add an event handler on it.  Lines 10 and 11 stop the default behavior of the browser.
 

Reading the content of the file

 
Now for the main part, that is reading the content of the file. For that, we will use the File Reader interface. The File Reader interface provides us the following methods to work with text and binary files.
  1. void readAsArrayBuffer(Blob blob);  
  2. void readAsText(Blob blob, optional DOMString encoding);  
  3. void readAsDataURL(Blob blob);
The 3rd method is used for reading the file content in the form of a Data URL. The second method is used for reading text-based files with supported encodings like UTF-8 and UTF-16. The first method is used for reading data as an array object.
 
Out of all these three methods, we will be using the second and third ones.
 
To read the file just add the following function script, HTML and style in your file.
 
HTML
  1. <div id="op"></div>  
  2. Style  
  3. #op{  
  4.   width:300px;  
  5.   height:300px;  
  6.   overflow:auto;  
  7.   background-color:rgba(221,214,221,0.3);  
  8.   border:1px dashed black;  
  9. }  
  10. Script  
  11. function getAsText(readFile) {  
  12.     var reader = new FileReader();  
  13.     reader.readAsText(readFile, "UTF-8");  
  14.     reader.onload = loaded;  
  15. }  
  16. function loaded(evt) {  
  17.     alert("File Loaded Successfully");  
  18.     var fileString = evt.target.result;  
  19.     $("#op").text(fileString);  
  20. }  
What we have done is that we have added the div having an id op (output) on which we will show the file text. We styled it a bit. In the script, function getAsText(readfile) basically creates the new FileReader object for reading the file. Then in the next line, we are using our readAsText() function to get the text from the file into the memory. It is an async function so we need to wait for its completion before we can use the text. We added the onload event on the reader object so that we get a notification as soon as the read is completed.
 
As the read completes it will call the loaded function. In the loaded function, we are simply showing the text of the function inside an op div. If you have done everything right so far then you are done. Check the following output. Oh! I forget to mention that you need to uncomment the call of getTextFile() from all of your read functions.
 
a8p8.JPG
 
a8p9.JPG
 
Now to read an Image file just replace your above functions with the following code.
  1. function startRead(evt) {  
  2.     var file = document.getElementById('file').files[0];  
  3.     if (file) {  
  4.         if (file.type.match("image.*")) {  
  5.             getAsImage(file);  
  6.             alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);  
  7.         }  
  8.         else {  
  9.             getAsText(file);  
  10.             alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);  
  11.         }  
  12.     }  
  13.     evt.stopPropagation();  
  14.     evt.preventDefault();  
  15. }  
  16.    
  17. function startReadFromDrag(evt) {  
  18.     var file = evt.dataTransfer.files[0];  
  19.     if (file) {  
  20.         if (file.type.match("image.*")) {  
  21.             getAsImage(file);  
  22.             alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);  
  23.         }  
  24.         else {  
  25.             getAsText(file);  
  26.             alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);  
  27.         }  
  28.     }  
  29.     evt.stopPropagation();  
  30.     evt.preventDefault();  
  31. }  
  32.    
  33. function getAsImage(readFile) {  
  34.    
  35.     var reader = new FileReader();  
  36.    
  37.     reader.readAsDataURL(readFile);  
  38.    
  39.     reader.onload = addImg;  
  40. }  
  41.    
  42. function addImg(imgsrc) {  
  43.     var img = document.createElement('img');  
  44.     img.setAttribute("src", imgsrc.target.result);  
  45.     document.getElementById("op").insertBefore(img);  
The code is not as big as it looks initially. It mostly contains the boilerplate code with slight modifications of previous methods. The getAsImage() method basically reads the image as a data URL and then sends it to "addImg()" which in turn creates a new img element and appends it in an op div. "File.type.match" is used to identify the type of file. Check the output below for the code above.
 
a8p10.JPG
 

Summary

 
All done. The upload completed successfully. In this article, I tried my best to provide you the minimal code required for the proper working of the uploader but you always can have a look at the API for other options available for it. If you find any problem then ask in comment. You can check the Demo HERE.