03、cordova-文件類插件

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 *">

主要的幾個(gè)對象:

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/轉(zhuǎn)換路徑)

1、requestFileSystem:僅兩個(gè)目錄 PERSISTENT / TEMPORARY

window.requestFileSystem(存儲類型,期望存儲空間大小(b字節(jié)),成功回調(diào),失敗回調(diào))
存儲類型:LocalFileSystem.PERSISTENT / LocalFileSystem.TEMPORARY
返回 FileSystem {name: string, root: DirectoryEntry}

window.requestFileSystem(
    LocalFileSystem.PERSISTENT,  //永久目錄
    //LocalFileSystem.TEMPORARY,  //臨時(shí)目錄
    0,  //如果是需要?jiǎng)?chuàng)建 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("錯(cuò)誤:" + file_error);
    }
);

2、window.resolveLocalFileSystemURL:可以轉(zhuǎn)換路徑(native file <-> cdvfile)

window.resolveLocalFileSystemURL("url", 成功回調(diào), 錯(cuò)誤回調(diào));

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("錯(cuò)誤:" + file_error);
    }
);

目錄操作:(創(chuàng)建/遍歷/刪除)

var entry = xxx;  //通過 requestFileSystem / resolveLocalFileSystemURL 獲得

entry.getDirectory(
    "new_path",
    {create: true},
    function (directory_entry) {
        alert("創(chuàng)建目錄成功");
    },
    function (file_error) {
        alert("錯(cuò)誤:" + file_error);
    }
);

entry.getDirectory(
    "",
    {create: false},
    function (directory_entry) {
        directory_entry.createReader().readEntries(  //如果 entry 已經(jīng)是 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("遍歷錯(cuò)誤:" + file_error);
            }
        );
    },
    function (file_error) {
        alert("錯(cuò)誤:" + file_error);
    }
);

entry.getDirectory(
    "new_path",  //注意:根目錄""不能夠刪除
    {create: false},
    function (directory_entry) {
        directory_entry.removeRecursively(  //如果 entry 已經(jīng)是 DirectoryEntry 可以直接從這步開始
            function(){
                alert("刪除目錄成功");
            },
            function (file_error) {
                alert("刪除目錄錯(cuò)誤:" + file_error);
            }
        );
    },
    function (file_error) {
        alert("錯(cuò)誤:" + file_error);
    }
);

文件操作:(創(chuàng)建/寫/追加/讀/刪除)

var entry = xxx;  //通過 requestFileSystem / resolveLocalFileSystemURL 獲得

//創(chuàng)建
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("寫入失敗");
                };
        
                // 移動(dòng)指針  === 追加寫入
                /*
                try {
                    fileWriter.seek(fileWriter.length);
                } catch (e) {
                    alert("移動(dòng)指針錯(cuò)誤:" + e);
                }
                */
        
                file_writer.write(blob);  //寫入內(nèi)容
            },
            function (file_error) {
                alert("寫入錯(cuò)誤:" + file_error);
            }
        );
    },
    function(file_error){
        alert("錯(cuò)誤:" + file_error);
    }
);

//讀取
entry.getFile(
    "file_name.txt",
    { create: false, exclusive: false },
    function (file_entry) {
        file_entry.file(  //如果 entry 已經(jīng)是 FileEntry 可以直接從這步開始
            function (file) {
                var reader = new FileReader();
                reader.onloadend = function () {
                    alert("讀取成功");
                    alert("讀取內(nèi)容:" + this.result);
                };
                reader.onerror = function(){
                    alert("讀取失敗");
                };
                reader.readAsText(file);
            },
            function (file_error) {
                alert("錯(cuò)誤:" + file_error);
            }
        );
    },
    function(file_error){
        alert("錯(cuò)誤:" + file_error);
    }
);

//刪除:
entry.getFile(
    "file_name.txt",
    { create: false, exclusive: false },
    function (file_entry) {
        file_entry.remove(  //如果 entry 已經(jīng)是 FileEntry 可以直接從這步開始
            function () {
                alert("刪除失敗");
            },
            function (file_error) {
                alert("刪除錯(cuò)誤:" + file_error);
            }
        );
    },
    function(file_error){
        alert("錯(cuò)誤:" + file_error);
    }
);

file transfer 文件上傳下載:

安裝:

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

上傳:

//參數(shù):
var options = new FileUploadOptions();
options.fileKey = "file";  //類型,默認(rèn)文件
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);  //文件名
options.httpMethod = "POST";  //默認(rèn)POST
options.mimeType = "text/plain";
options.trustAllHosts = true;  //是否接受所有證書 默認(rèn)false
options.params = {  //請求參數(shù) 鍵值對
    value1:"test",
    value2:"param"
};

var ft = new FileTransfer();
//upload(文件路徑,上傳路徑(encodeURI編碼),成功回調(diào),失敗回調(diào),參數(shù));
ft.upload("",
    encodeURI("http://some.server.com/upload.php"),
    function(file_upload_result){
        alert("響應(yīng)碼:" + file_upload_result.responseCode);
        alert("響應(yīng):" + file_upload_result.response);
        alert("發(fā)送字節(jié)數(shù):" + file_upload_result.bytesSent);
    },
    function(error){
        alert("錯(cuò)誤碼:" + error.code);
        alert("錯(cuò)誤資源:" + error.source);
        alert("錯(cuò)誤目標(biāo):" + error.target);
    },
    options
);

下載:

var fileTransfer = new FileTransfer();
//download(下載路徑(encodeURI), 存儲位置,成功回調(diào),錯(cuò)誤回調(diào),是否信任所有證書,參數(shù))
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();  //會給回調(diào)函數(shù)返回錯(cuò)誤:FileTransferError.ABORT_ERR

file opener2 本地默認(rèn)軟件打開文件:

安裝:

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("成功")}
    }
);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容