phonegap file操作

来源:互联网 发布:淘宝帐号实名认证在哪 编辑:程序博客网 时间:2024/04/29 15:56

phonegap中,有时候需要操作到手机中的文件,这个时候就需要用到phonegap官方提供的插件 file ,英文好的可以直接参考官方文档

首先是安装插件:(需要phonegap 3.0 以上,不止如何用命令行安装插件请自行百度)

cordova plugin add org.apache.cordova.file

今天主要介绍这个插件中的FileReader,总共有以下的几个方法

  • abort: 终止读取文件.
  • readAsDataURL: 读取文件然后返回 base64格式的url
  • readAsText: 读取文件然后返回文本.
  • readAsBinaryString: 读取文件然后返回字节.
  • readAsArrayBuffer: Reads file as an ArrayBuffer.
有以下的属性
  • readyState: 当前读取器所处的状态,取值为以下三者之一:EMPTY、LOADING和DONE。
  • result:已读取文件的内容。(DOMString类型)
  • error:包含错误信息的对象。(FileError类型)
  • onloadstart:读取启动时调用的回调函数。(函数类型)
  • onprogress:读取过程中调用的回调函数,用于汇报读取进度(progress.loaded和progress.total)。(函数类型) 不支持
  • onload:读取安全完成后调用的回调函数。(函数类型)
  • onabort:读取被中止后调用的回调函数,例如通过调用abort()方法。(函数类型)
  • onerror:读取失败后调用的回调函数。(函数类型)
  • onloadend:请求完成后调用的回调函数(无论请求是成功还是失败)。(函数类型)

简单的例子:

<!DOCTYPE html><html>  <head>    <title>FileReader Example</title>    <script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>    <script type="text/javascript" charset="utf-8">    // Wait for device API libraries to load    //    function onLoad() {        document.addEventListener("deviceready", onDeviceReady, false);    }    // device APIs are available    //    function onDeviceReady() {        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);    }    function gotFS(fileSystem) {        fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);    }    function gotFileEntry(fileEntry) {        fileEntry.file(gotFile, fail);    }    function gotFile(file){        readDataUrl(file);        readAsText(file);    }    function readDataUrl(file) {        var reader = new FileReader();        reader.onloadend = function(evt) {            console.log("Read as data URL");            console.log(evt.target.result);        };        reader.readAsDataURL(file);    }    function readAsText(file) {        var reader = new FileReader();        reader.onloadend = function(evt) {            console.log("Read as text");            console.log(evt.target.result);        };        reader.readAsText(file);    }    function fail(evt) {        console.log(evt.target.error.code);    }    </script>  </head>  <body>    <h1>Example</h1>    <p>Read File</p>  </body></html>

其中标1 的地方,则是成功读取文件的时候所返回的结果,例子中得到的evt.target.result中 的内容便是 base64格式的url,你可以将它放到<img>便签中的src中显示出来

转载自:http://chenblog.sinaapp.com

0 0
原创粉丝点击