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 file 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.

 <script>

    if (window.File && window.FileReader && window.FileList && window.Blob) {

        alert("File API supported.!");

    } else {

        alert('The File APIs are not fully supported in this browser.');

    }

</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 selection 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:

readonly attribute DOMString name;
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.

function startRead(evt) {

    var file = document.getElementById('file').files[0];

    if (file) {

        //  getAsText(file);

        alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);

    }

}

 

Now in your HTML input tag add an onchange event and call this function as in the following:

 

<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:

<div id="draghere" >Drop files here</div>

 

#draghere{

  width:300px;

  height:100px;

  background-color:rgba(221,214,155,0.4);

  border:1px dashed black;

  text-align:center;

}

The code is simple. The HTML line basically provides a div for which the user can drag the file to begin an 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 stops 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.

void readAsArrayBuffer(Blob blob);

void readAsText(Blob blob, optional DOMString encoding);

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 encoding 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

<div id="op"></div>

Style

#op{

  width:300px;

  height:300px;

  overflow:auto;

  background-color:rgba(221,214,221,0.3);

  border:1px dashed black;

}

Script

function getAsText(readFile) {

    var reader = new FileReader();

    reader.readAsText(readFile, "UTF-8");

    reader.onload = loaded;

}

function loaded(evt) {

    alert("File Loaded Successfully");

    var fileString = evt.target.result;

    $("#op").text(fileString);

}

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 it's completion before we can use the text. We added the onload event on the reader object so that we get 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.

function startRead(evt) {

    var file = document.getElementById('file').files[0];

    if (file) {

        if (file.type.match("image.*")) {

            getAsImage(file);

            alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);

        }

        else {

            getAsText(file);

            alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);

        }

    }

    evt.stopPropagation();

    evt.preventDefault();

}

 

function startReadFromDrag(evt) {

    var file = evt.dataTransfer.files[0];

    if (file) {

        if (file.type.match("image.*")) {

            getAsImage(file);

            alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);

        }

        else {

            getAsText(file);

            alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);

        }

    }

    evt.stopPropagation();

    evt.preventDefault();

}

 

function getAsImage(readFile) {

 

    var reader = new FileReader();

 

    reader.readAsDataURL(readFile);

 

    reader.onload = addImg;

}

 

function addImg(imgsrc) {

    var img = document.createElement('img');

    img.setAttribute("src", imgsrc.target.result);

    document.getElementById("op").insertBefore(img);

}

The code is not as big as it looks initially. It mostly contains the boiler plate 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 .

Up Next
    Ebook Download
    View all
    Learn
    View all