Article From:
Original: Html5 Learning Series (four) file operation API

    Before we operate local files, we use flash, Silverlight, or third party activeX plug-ins, and it’s hard to perform a cross platform, cross browser, cross device, and so on, and from another point of view.That is to say, our web applications rely on third party plug-ins, rather than being independent and not versatile. In the HTML5 standard, the API of the operation file is provided by default, so that all of these can be standardized directly. With the API of the operation file, our Web application can be easily controlled by JS.File reading, writing, folder, file and a series of operations, so that the Web application is no longer so poor, and before the Web application without the use of third party plug-ins, that is a shit! However, most browsers in the latest standards have already read API, files, and files.The latest standards for parts and folders have just been set up. I believe that these features will be very good with the upgrade of the browser. Next, I will give you a brief introduction of several API read files.

Several important JS objects

  It is a collection of File objects. In the Html4 standard, the file upload control accepts only one file, and in the new standard, only multiple is set up to support multiple file uploads, so the files attribute obtained from this label is an instance of the FileList object. DEmo:< input type= “file” multiple= “multiple” name= “fileDemo” id= “fileDemo” />API’s prototype:It

interface FileList {
      getter File? item(unsigned long index);
      readonly attribute unsigned long length;


In fact, it is a raw data object, which provides the slice method to read a piece of data in the original data. There are two properties: size (data size), type (MIME type of data); look at the following API prototype of W3C:

    interface Blob {
      readonly attribute unsigned long long size;
      readonly attribute DOMString type;
      //slice Blob into byte-ranged chunks     
      Blob slice(optional long long start,
                 optional long long end,
                 optional DOMString contentType); 

Inherit from the Blob object, pointing to a specific file, it has two properties: name (filename), lastModifiedDate (last modified time); and then let’s see some of the W3C standards:

 interface File : Blob {

          readonly attribute DOMString name;
          readonly attribute Date lastModifiedDate;

It is designed to read the data in the file, provide three common methods to read the file data, and read the file data in an asynchronous way, very efficient. Then let’s look at some of the W3C standards:

    interface FileReader: EventTarget {

      // async read methods
      void readAsArrayBuffer(Blob blob);
      void readAsBinaryString(Blob blob);
      void readAsText(Blob blob, optional DOMString encoding);
      void readAsDataURL(Blob blob);

      void abort();

      // states  
      const unsigned short EMPTY = 0;
      const unsigned short LOADING = 1;
      const unsigned short DONE = 2;

      readonly attribute unsigned short readyState;

      // File or Blob data
      readonly attribute any result;

      readonly attribute DOMError error;

      // event handler attributes
      attribute [TreatNonCallableAsNull] Function? onloadstart;
      attribute [TreatNonCallableAsNull] Function? onprogress;
      attribute [TreatNonCallableAsNull] Function? onload;
      attribute [TreatNonCallableAsNull] Function? onabort;
      attribute [TreatNonCallableAsNull] Function? onerror;
      attribute [TreatNonCallableAsNull] Function? onloadend;


This object is a very important first object, which provides four methods to read file data that reads data asynchronously and puts the result directly into the property result after the reading is successful. So it is usually the direct reading of data and then monitoring the onload event of this object.Then read the result attribute in the event and do the subsequent processing. Of courseabortIt is the way to stop reading. The other is that events and states are no longer described.

The three methods are introduced.

readAsBinaryString(Blob blob);  → A Blob object is passed in, and the result of reading the data is placed in the form of binary string.FileReaderIn the result attribute.

readAsText(Blob blob, optional DOMString encoding);→The first parameter is passed into the Blog object, then the second parameters are passed into the encoding format, which asynchronously puts the data read successfully into the result property, and the content is read in the form of a common text string.

readAsDataURL(Blob blob);Pass in a Blob object,The content can be read as the URL attribute, that is to say, the result of a picture can be pointed to the SRC attribute of a img. “”

Read the files uploaded from the control and display the contents in different ways to the browser instance.

  Before we display the code, we operate a picture file before uploading the picture to the server, then using a img tag to point to the URL address of the server, and then use a third party plug-in for image processing, and now all this does not need the server side, because FThe way ileReader objects provide several reading files is extremely simple and is not the operation of client JS. And look at the following Demo:

Case 1: get the file name of the uploaded file (online presentation address)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
    <script src="Scripts/jquery-1.5.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGetFile").click(function (e) {
                var fileList = document.getElementById("fileDemo").files;
                for (var i = 0; i < fileList.length; i++) {
                    if (!(/image\/\w+/.test(fileList[i].type))) {
                         $("#result").append("<span>type:"+fileList[i].type+"--******Non image type *****--name: "+fileList[i].name+" --size: "+fileList[i].size+" < /span> < br /> "";}Else {$("#result").Append ("< span&g")T; type: "+fileList[i].type+" --name: "+fileList[i].name+" --size: "+fileList[i].size+" < /span> < br/> ");}}});});< /script>< /head>< body>< form action= "/home/index" method= "POST" novalidate= "true".>< input type= "file" multiple= "multiple" name= "fileDemo" id= "fileDemo" /> fileDemo;T;< input type= "button" value= "get the name of the file" id= "btnGetFile" />< div id= "result"> < /div>< /form>< hr/>< /body>< /html>


Case two: read the contents of the uploaded file, and then read the contents of the file directly to the browser (online address)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
    <script src="Scripts/jquery-1.5.1.js" type="text/javascript"></script>  
    <script type="text/javascript">
        if(typeof FileReader == "undified") {
            alert("Your old browser is not good! ");}Function showDataByURL () {Var resultFile = documenT.getElementById ("fileDemo").Files[0];If (resultFile) {Var reader =New FileReader ();Reader.readAsDataURL (resultFile);Reader.onload = function (E) {Var urlData = this.result;Document.getElementById ("result").InnerHTML + = "< img src='" + urlData + "" alt=' "+ + "/>";};}}Function showDataByBinaryString () {Var resultFile = document.getElementByID ("fileDemo").Files[0];If (resultFile) {Var reader = new FileReader ();/ / asynchronous mode, it does not affect the main threadReader.readAsBinaryString (resultFile);Reader.onload = function (E) {Var urlData = this.resuLt;Document.getElementById ("result").InnerHTML + = urlData;};}}Function showDataByText () {Var resultFile = doCument.getElementById ("fileDemo").Files[0];If (resultFile) {Var readEr = new FileReader ();Reader.readAsText (resultFile,'gb2312');REader.onload = function (E) {Var urlData = this.result;DOcument.getElementById ("result").InnerHTML + = urlData;};}}< /script>< /head>< body>< input type= "file" name= "fileDeMo "id=" fileDemo "multep/>< input type= "button" value= "readAsDataURL" id= "readAsDataURL".Onclick= "showDataByURL ()"; "/>< input type= "button" value= "readAsBinaryString" id= "readAsB"InaryString "onclick=" showDataByBinaryString (); "/>";< input type= "button" value= "readAsText"Id=" readAsText "onclick=" showDataByText (); "/>";< div id= "result" ></div>< /body>< /html>



       With the file operation of API, let JS further operate local files to an unprecedented enhancement, HTML5 for client Web applications to get further functionality, the HTML5 trend to make Web more rich client, and these all need to let our HTML or JS becomeMore powerful, and HTML5 launched File API in due course.

Leave a Reply

Your email address will not be published. Required fields are marked *