程序员Android开发Android知识

03、cordova-文件类插件

2017-03-21  本文已影响1023人  魔力小小鸟

File:文件读取

安装:

cordova plugin add cordova-plugin-file --save
cordova plugin rm cordova-plugin-file --save

配置 cdvfile:

config.xml:

<access origin="cdvfile://*" />

index.html: Content-Security-Policy 增加 cdvfile:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap:cdvfile:https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

主要的几个对象:

FileSystem
Entry
DirectoryEntry
FileEntry

三种路径格式:

//第一种:file
alert("file:///x/y/z/");

//第二种:cdvdile
alert("cdvfile://localhost/persistent/x/y/z");
alert("cdvfile://localhost/temporary/x/y/z");

//第三种:
alert(cordova.file.applicationDirectory);
alert(cordova.file.applicationStorageDirectory);
alert(cordova.file.dataDirectory);
alert(cordova.file.cacheDirectory);
alert(cordova.file.externalApplicationStorageDirectory);
alert(cordova.file.externalDataDirectory);
alert(cordova.file.externalCacheDirectory);
alert(cordova.file.externalRootDirectory);
alert(cordova.file.tempDirectory);
alert(cordova.file.syncedDataDirectory);
alert(cordova.file.documentsDirectory);
alert(cordova.file.sharedDirectory);

路径操作:(获取Entry/转换路径)

1、requestFileSystem:仅两个目录 PERSISTENT / TEMPORARY

window.requestFileSystem(存储类型,期望存储空间大小(b字节),成功回调,失败回调)
存储类型:LocalFileSystem.PERSISTENT / LocalFileSystem.TEMPORARY
返回 FileSystem {name: string, root: DirectoryEntry}

window.requestFileSystem(
    LocalFileSystem.PERSISTENT,  //永久目录
    //LocalFileSystem.TEMPORARY,  //临时目录
    0,  //如果是需要创建 PERSISTENT 永久文件 需要为0
    function (fs) {  //fs FileSystem  {name: string, root: DirectoryEntry}
        alert("fs名字:" + fs.name);  //persistent
        alert("DirectoryEntry:"+fs.root);  // DirectoryEntry 对象
        alert("DirectoryEntry isFile:"+fs.root.isFile);  //false
        alert("DirectoryEntry isDirectory:"+fs.root.isDirectory);  //true
        alert("DirectoryEntry name:"+fs.root.name);  //""
        alert("DirectoryEntry fullPath:"+fs.root.fullPath);  // /
        alert("DirectoryEntry fileSystem:"+fs.root.fileSystem);  // undefined
        alert("DirectoryEntry nativeURL:"+fs.root.nativeURL);  // file:///data/data/com.example.hello/files/files/
    },
    function (file_error) {
        alert("错误:" + file_error);
    }
);

2、window.resolveLocalFileSystemURL:可以转换路径(native file <-> cdvfile)

window.resolveLocalFileSystemURL("url", 成功回调, 错误回调);

var native_path = "file:///";
// var cdvfile_path = "cdvfile://localhost/persistent/";
window.resolveLocalFileSystemURL(
    native_path,
    //cdvfile_path,
    function (entry) {
        alert("entry isFile:"+entry.isFile);  //false
        alert("entry isDirectory:"+entry.isDirectory);  //true
        alert("entry name:"+entry.name);  //""
        alert("entry fullPath:"+entry.fullPath);  // /
        alert("entry fileSystem:"+entry.fileSystem);  // undefined
        alert("entry nativeURL:"+entry.nativeURL);  // file:///data/data/com.example.hello/files/files/
        alert('entry toURL: ' + entry.toURL());  // file:///data/data/com.example.hello/files/files/
        alert('entry toInternalURL: ' + entry.toInternalURL());  // cdvfile://localhost/persistent/
    },
    function(file_error){
        alert("错误:" + file_error);
    }
);

目录操作:(创建/遍历/删除)

var entry = xxx;  //通过 requestFileSystem / resolveLocalFileSystemURL 获得

entry.getDirectory(
    "new_path",
    {create: true},
    function (directory_entry) {
        alert("创建目录成功");
    },
    function (file_error) {
        alert("错误:" + file_error);
    }
);

entry.getDirectory(
    "",
    {create: false},
    function (directory_entry) {
        directory_entry.createReader().readEntries(  //如果 entry 已经是 DirectoryEntry 可以直接从这步开始
            function(entry_array){
                alert("遍历目录:");
                for(var index in entry_array){
                    alert(entry_array[index].toURL());  //native file
                    alert(entry_array[index].toInternalURL());  //cdvfile
                }
            },
            function (file_error) {
                alert("遍历错误:" + file_error);
            }
        );
    },
    function (file_error) {
        alert("错误:" + file_error);
    }
);

entry.getDirectory(
    "new_path",  //注意:根目录""不能够删除
    {create: false},
    function (directory_entry) {
        directory_entry.removeRecursively(  //如果 entry 已经是 DirectoryEntry 可以直接从这步开始
            function(){
                alert("删除目录成功");
            },
            function (file_error) {
                alert("删除目录错误:" + file_error);
            }
        );
    },
    function (file_error) {
        alert("错误:" + file_error);
    }
);

文件操作:(创建/写/追加/读/删除)

var entry = xxx;  //通过 requestFileSystem / resolveLocalFileSystemURL 获得

//创建
entry.getFile(
    "file_name.txt",
    { create: true, exclusive: false },
    function (file_entry) {
        //写入
        var blob = new Blob(
                    ['测试测试测试测试测试'],
                    {type: 'text/plain'}
                 );
        file_entry.createWriter(
            function (file_writer) {
                file_writer.onwriteend = function () {
                    alert("写入完成");
                };
                file_writer.onerror = function (e) {
                    alert("写入失败");
                };
        
                // 移动指针  === 追加写入
                /*
                try {
                    fileWriter.seek(fileWriter.length);
                } catch (e) {
                    alert("移动指针错误:" + e);
                }
                */
        
                file_writer.write(blob);  //写入内容
            },
            function (file_error) {
                alert("写入错误:" + file_error);
            }
        );
    },
    function(file_error){
        alert("错误:" + file_error);
    }
);

//读取
entry.getFile(
    "file_name.txt",
    { create: false, exclusive: false },
    function (file_entry) {
        file_entry.file(  //如果 entry 已经是 FileEntry 可以直接从这步开始
            function (file) {
                var reader = new FileReader();
                reader.onloadend = function () {
                    alert("读取成功");
                    alert("读取内容:" + this.result);
                };
                reader.onerror = function(){
                    alert("读取失败");
                };
                reader.readAsText(file);
            },
            function (file_error) {
                alert("错误:" + file_error);
            }
        );
    },
    function(file_error){
        alert("错误:" + file_error);
    }
);

//删除:
entry.getFile(
    "file_name.txt",
    { create: false, exclusive: false },
    function (file_entry) {
        file_entry.remove(  //如果 entry 已经是 FileEntry 可以直接从这步开始
            function () {
                alert("删除失败");
            },
            function (file_error) {
                alert("删除错误:" + file_error);
            }
        );
    },
    function(file_error){
        alert("错误:" + file_error);
    }
);

file transfer 文件上传下载:

安装:

cordova plugin add cordova-plugin-file-transfer --save
cordova plugin rm cordova-plugin-file-transfer --save

上传:

//参数:
var options = new FileUploadOptions();
options.fileKey = "file";  //类型,默认文件
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);  //文件名
options.httpMethod = "POST";  //默认POST
options.mimeType = "text/plain";
options.trustAllHosts = true;  //是否接受所有证书 默认false
options.params = {  //请求参数 键值对
    value1:"test",
    value2:"param"
};

var ft = new FileTransfer();
//upload(文件路径,上传路径(encodeURI编码),成功回调,失败回调,参数);
ft.upload("",
    encodeURI("http://some.server.com/upload.php"),
    function(file_upload_result){
        alert("响应码:" + file_upload_result.responseCode);
        alert("响应:" + file_upload_result.response);
        alert("发送字节数:" + file_upload_result.bytesSent);
    },
    function(error){
        alert("错误码:" + error.code);
        alert("错误资源:" + error.source);
        alert("错误目标:" + error.target);
    },
    options
);

下载:

var fileTransfer = new FileTransfer();
//download(下载路径(encodeURI), 存储位置,成功回调,错误回调,是否信任所有证书,参数)
fileTransfer.download(
    encodeURI("http://some.server.com/download.php"),
    "filepath",
    function(entry) {
        console.log("download complete: " + entry.toURL());
    },
    function(error) {
        console.log("download error source " + error.source);
        console.log("download error target " + error.target);
        console.log("download error code" + error.code);
    },
    true,
    {
        headers: {
            // "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
        }
    }
);

中止:

ft.abort();  //会给回调函数返回错误:FileTransferError.ABORT_ERR

file opener2 本地默认软件打开文件:

安装:

cordova plugin add cordova-plugin-file-opener2 --save
cordova plugin rm cordova-plugin-file-opener2 --save

使用:

cordova.plugins.fileOpener2.open(
    //文件路径:格式:"/sdcard/Download/starwars.pdf"
    //也可以是 cdvfile 格式 "cdvfile://localhost/persistent/Download/starwars.pdf"
    "filePath",
    "fileMIMEType",  //文件类型'application/pdf',
    {
        error : function(e){alert("失败"+e)},
        success : function(){alert("成功")}
    }
);
上一篇下一篇

猜你喜欢

热点阅读