How to read text file in client side via HTML5


In HTML4, As we known, if you want to read a local text file with javascript, you may need to use ActiveX object, there is a blog describes how to read text file by using ActiveX, clickhere. In other words, this solution cannot work on another browser, just like: Firefox, Opera, Safari, etc.

But now, we have HTML5, it supports we read local file via FileReader, it's an interface that provides methods to read file objects or blog objects into memory, it's asynchronous call.

OK, let me show how to read a local text file by using FileReader.




    
    
    


    
    


You need to run the above HTML page in IE9 or another browser which supports HTML5.

Attention please, because the reading action is asynchronous, so you need to call a callback function in onloadend event.

Extending this topic

  • Methods of the FileReader interface

Function name
Parameters
Description
readAsBinaryString file it reads file as binary code
readAsText file, [encoding] it reads file as text
readAsDataURL file it reads file as DataURL
abort (none) interrupt reading


  • Events of the FileReader interface

Event
Description
onabort it's triggered while interrupting reading
onerror it's triggered while occurring error
onloadstart it's triggered while starting reading
onprogress it's triggered while processing reading
onload it's triggered while finishing reading successful
onloadend it's triggered while finishing reading, whatever successful or failed

You can read file as binary code or DataURL type, so you can do more optional things, for example, you can provide a download window via DataURL, and never go through the server side, if you want to know something about Data URI, clickhere, it introduces what'sData URI scheme.

And you also can read file content in client side, and display them, so that you have  no need to upload them to server side just for file preview.

你可能感兴趣的:(HTML5)