Html5 学习系列(四)文件操做API

原文: Html5 学习系列(四)文件操做API

引言

    在以前咱们操做本地文件都是使用flash、silverlight或者第三方的activeX插件等技术,因为使用了这些技术后就很难进行跨平台、或者跨浏览器、跨设备等状况下实现统一的表现,从另一个角度来讲就是让咱们的web应用依赖了第三方的插件,而不是很独立,不够通用。在HTML5标准中,默认提供了操做文件的API让这一切直接标准化。有了操做文件的API,让咱们的Web应用能够很轻松的经过JS来控制文件的读取、写入、文件夹、文件等一系列的操做,让Web应用再也不那么蹩脚,而以前Web应用若是不借助第三方插件,那就是个shit!可是最新的标准中大部分浏览器都已经实现了文件的读取API,文件的写入,文件和文件夹的最新的标准刚制定完毕,相信后面随着浏览器的升级这些功能确定会实现的很是好,接下来我主要给你们介绍文件读取的几个API。javascript

几个重要的JS对象

1):FileList对象
  它是File对象的一个集合,在Html4标准中文件上传控件只接受一个文件,而在新标准中,只须要设置multiple,就支持多文件上传,因此今后标签中获取的files属性就是FileList对象实例。demo:<input type="file" multiple="multiple" name="fileDemo" id="fileDemo" />  ;下面是关于FileList对象的API的原型:  html

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

2)Blob对象java

其实就是一个原始数据对象,它提供了slice方法能够读取原始数据中的某块数据。另外有两个属性:size(数据的大小),type(数据的MIME类型);看下面的是W3C的API原型:jquery

    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); 
    
    };

3)File对象
继承自Blob对象,指向一个具体的文件,它还有两个属性:name(文件名), lastModifiedDate(最后修改时间);而后让咱们看一些W3C的标准:
web

 interface File : Blob {

          readonly attribute DOMString name;
          readonly attribute Date lastModifiedDate;
 };

4)FileReader对象
设计用来读取文件里面的数据,提供三个经常使用的读取文件数据的方法,另外读取文件数据使用了异步的方式,很是高效。而后让咱们看一些W3C的标准:浏览器

[Constructor]
    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;

    };

这个对象是很是重要第一个对象,它提供了四个读取文件数据的方法,这些方法都是异步的方式读取数据,读取成功后就直接将结果放到属性result中。因此通常就是直接读取数据,而后监听此对象的onload事件,而后在事件里面读取result属性,再作后续处理。固然abort就是中止读取的方法。其余的就是事件和状态再也不赘述。服务器

三个方法都介绍一下:app

readAsBinaryString(Blob blob);  → 传入一个Blob对象,而后读取数据的结果做为二进制字符串的形式放到FileReader的result属性中。异步

readAsText(Blob blob, optional DOMString encoding);→第一个参数传入Blog对象,而后第二个参数传入编码格式,异步将数据读取成功后放到result属性中,读取的内容是普通的文本字符串的形式。async

readAsDataURL(Blob blob);传入一个Blob对象,读取内容能够作为URL属性,也就是说能够将一个图片的结果指向给一个img的src属性。                                  

读取文件上传控件里的文件并将内容已不一样的方式展示到浏览器里面实例

  在展现代码以前,以前咱们操做一个图片文件,都是先将图片上传到服务器端,而后再使用一个img标签指向到服务器的url地址,而后再进行一个使用第三方插件进行图片处理,而如今这一切都不须要服务器端了,由于FileReader对象提供的几个读取文件的方法变得异常简单,并且全不是客户端js的操做。且看下面的demo:

案例一:获取上传文件的文件名(在线演示地址)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <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+"--******非图片类型*****--name:"+fileList[i].name+"--size:"+fileList[i].size+"</span><br />");
                    }
                    else {
                        $("#result").append("<span>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" /><br/>
        <input type="button" value="获取文件的名字" id="btnGetFile"/>
        <div id="result"></div>
    </form>
    <hr/>
</body>
</html>

 

案例二:读取上传文件内容,而后将文件内容直接读取到浏览器上(在线演示地址)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.5.1.js" type="text/javascript"></script>  
    <script type="text/javascript">
        
        if(typeof FileReader == "undified") {
            alert("您老的浏览器不行了!");
        }

        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='" + resultFile.name + "' />";
                }; 
               
            }
            
        } 

        function showDataByBinaryString() {
              var resultFile = document.getElementById("fileDemo").files[0];
            if (resultFile) {
                var reader = new FileReader();
                //异步方式,不会影响主线程
                reader.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="readAsBinaryString" onclick="showDataByBinaryString();"/>
    <input type="button" value="readAsText"  id="readAsText" onclick="showDataByText();"/>
    <div id="result">
        
    </div>

</body>
</html>

 

总结

       有了文件操做的API后,让JS进一步的操做本地文件的获得空前的增强,HTML5对于客户端Web应用获得进一步功能的提高,HTML5的趋势让Web更加富客户端化,而这些都须要让咱们的HTML或者JS变得更增强大,而HTML5正是适时地推出了File API!

相关文章
相关标签/搜索