Read local files and metadata using HTML5 without uploading to server

Advertisement

HTML5 comes with a array of features which breaks away from traditional file reading, file upload method. It provides a FileReader object which provides you lots of functions to manipulate the local files in the user system without having them uploaded to server. This provides great benefits when you need to perform file types checking, size etc of user uploaded content on the browser itself by reducing load on your server.

Below example is based on HTML5, JQuery using FileReader object. This simple example shows how to add an “INPUT” tag, read the file name, file size, file type and read the content.

HTML

First we will declare an INPUT tag to let user choose a file using ‘Browse’ button. Also we will add some placeholder to display the file and its metadata.

Catch the Event

Then we will add some code to handle the event when user chooses a file. It can be done using the ‘change’ event of the INPUT tag. As soon as user chooses a file using Browse/Choose File button, the ‘change’ event gets triggered.


$(document).ready(function() {
$("#myfile").change(function() {
// Your code to handle the file
});
});

Now we caught the change event and its time to get hold of the file.

Hold the file and read its metadata

Once we get hold of the file, we can accesses all of its properties through ‘this’ or JQuery as below.


var thefile = $("#myfile").get(0).files[0];

Lets read some of the file properties and display on the screen.

Read the file using FileReader

Now its time to read the content of the file. HTML5 provides FileReader interface which can be used to read a local file as text/binary/blob objects. In this example, we will read the file as binary string.

Create a new instance of the FileReader interface using its constructor. Define a function to catch reader’s onload event and get the file data through Filereader’s ‘result’ properties.


var reader = new FileReader(); // Declare a new file reader
reader.onload = function(e) {
$("#fcontent").text("File Content: " + reader.result); // Show the file content
}

We have declared all functions, its time to read the file by calling readAsBinaryString method of FileReader.


reader.readAsBinaryString(thefile);  // Read the file

Complete Code:





file read



A simple JQuery HTML5 file read Demo using FileReader.

Upload a file using below button below and see the file details.




You may also like...

Translate »