H5基础(4)-HTML5文件操作API

来源:互联网 发布:python下载后怎么使用 编辑:程序博客网 时间:2024/06/05 00:55

几个重要的JS对象

1.1:FileList对象

它是File对象的一个集合,在HTML4标准中文件上传控件只接受一个文件,而在新标准中,只需要设置multiple,就支持多文件上传,所以从此标签中获取的files属性就是FileList对象实例。
demo:

<input type="file" multiple="multiple" name="fileDemo" id="fileDemo" />;

下面是关于FileList对象的API的原型:

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

1.2:Blob对象

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

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

1.3:File对象

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

interface File : Blob {    readonly attribute DOMString name;    readonly attribute Date lastModifiedDate;};

1.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就是停止读取的方法。

FileReader对象的三个读取文件数据方法:

  • readAsBinaryString(Blob blob)传入一个Blob对象,然后读取数据的结果作为二进制字符串的形式放到FileReader的result属性中。
  • readAsText(Blob blob,optional DOMString encoding)
    第一个参数传入Blob对象,然后第二个参数传入编码格式,异步将数据读取成功后放到result属性中,读取的内容是普通的文本字符串的形式。
  • readAsDataURL(Blob blob)
    传入一个Blob对象,读取内容可以做为URL属性,也就是说可以将一个图片的结果指向给一个img的src属性。

读取文件上传控件里的文件并将内容已不同的方式展现到浏览器

操作一个图片文件,都是先将图片上传到服务器端,然后再使用一个img标签指向到服务器的url地址,然后再进行一个使用第三方插件进行图片处理,而现在这一切都不需要服务器端了,因为FileReader对象提供的几个读取文件的方法变得异常简单,而且全部是客户端js的操作。

实例一:获取上传文件的文件名(注:需要引入jQuery)

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

实例二:读取上传文件内容,然后将文件内容直接读取到浏览器上(注:需要引入jQuery)

<!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>
原创粉丝点击