03、cordova-文件類(lèi)插件

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è)對(duì)象:

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(存儲(chǔ)類(lèi)型乖阵,期望存儲(chǔ)空間大小(b字節(jié))栖疑,成功回調(diào),失敗回調(diào))
存儲(chǔ)類(lèi)型: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 對(duì)象
        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;  //通過(guò) 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 可以直接從這步開(kāi)始
            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 可以直接從這步開(kāi)始
            function(){
                alert("刪除目錄成功");
            },
            function (file_error) {
                alert("刪除目錄錯(cuò)誤:" + file_error);
            }
        );
    },
    function (file_error) {
        alert("錯(cuò)誤:" + file_error);
    }
);

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

var entry = xxx;  //通過(guò) requestFileSystem / resolveLocalFileSystemURL 獲得

//創(chuàng)建
entry.getFile(
    "file_name.txt",
    { create: true, exclusive: false },
    function (file_entry) {
        //寫(xiě)入
        var blob = new Blob(
                    ['測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試'],
                    {type: 'text/plain'}
                 );
        file_entry.createWriter(
            function (file_writer) {
                file_writer.onwriteend = function () {
                    alert("寫(xiě)入完成");
                };
                file_writer.onerror = function (e) {
                    alert("寫(xiě)入失敗");
                };
        
                // 移動(dòng)指針  === 追加寫(xiě)入
                /*
                try {
                    fileWriter.seek(fileWriter.length);
                } catch (e) {
                    alert("移動(dòng)指針錯(cuò)誤:" + e);
                }
                */
        
                file_writer.write(blob);  //寫(xiě)入內(nèi)容
            },
            function (file_error) {
                alert("寫(xiě)入錯(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 可以直接從這步開(kāi)始
            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 可以直接從這步開(kāi)始
            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";  //類(lèi)型什燕,默認(rèn)文件
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);  //文件名
options.httpMethod = "POST";  //默認(rèn)POST
options.mimeType = "text/plain";
options.trustAllHosts = true;  //是否接受所有證書(shū) 默認(rèn)false
options.params = {  //請(qǐng)求參數(shù) 鍵值對(duì)
    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), 存儲(chǔ)位置事富,成功回調(diào)技俐,錯(cuò)誤回調(diào),是否信任所有證書(shū)统台,參數(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();  //會(huì)給回調(diào)函數(shù)返回錯(cuò)誤:FileTransferError.ABORT_ERR

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

安裝:

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",  //文件類(lèi)型'application/pdf',
    {
        error : function(e){alert("失敗"+e)},
        success : function(){alert("成功")}
    }
);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末雕擂,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子贱勃,更是在濱河造成了極大的恐慌捂刺,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,464評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件募寨,死亡現(xiàn)場(chǎng)離奇詭異族展,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)拔鹰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,033評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)仪缸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人列肢,你說(shuō)我怎么就攤上這事恰画。” “怎么了瓷马?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,078評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵拴还,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我欧聘,道長(zhǎng)片林,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,979評(píng)論 1 299
  • 正文 為了忘掉前任怀骤,我火速辦了婚禮费封,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蒋伦。我一直安慰自己弓摘,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,001評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布痕届。 她就那樣靜靜地躺著韧献,像睡著了一般末患。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上锤窑,一...
    開(kāi)封第一講書(shū)人閱讀 52,584評(píng)論 1 312
  • 那天璧针,我揣著相機(jī)與錄音,去河邊找鬼果复。 笑死陈莽,一個(gè)胖子當(dāng)著我的面吹牛渤昌,可吹牛的內(nèi)容都是我干的虽抄。 我是一名探鬼主播,決...
    沈念sama閱讀 41,085評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼独柑,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼迈窟!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起忌栅,我...
    開(kāi)封第一講書(shū)人閱讀 40,023評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤车酣,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后索绪,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體湖员,經(jīng)...
    沈念sama閱讀 46,555評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,626評(píng)論 3 342
  • 正文 我和宋清朗相戀三年瑞驱,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了娘摔。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,769評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡唤反,死狀恐怖凳寺,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情彤侍,我是刑警寧澤肠缨,帶...
    沈念sama閱讀 36,439評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站盏阶,受9級(jí)特大地震影響晒奕,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜名斟,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,115評(píng)論 3 335
  • 文/蒙蒙 一吴汪、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蒸眠,春花似錦漾橙、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,601評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)脾歇。三九已至,卻和暖如春淘捡,著一層夾襖步出監(jiān)牢的瞬間藕各,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,702評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工焦除, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留激况,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,191評(píng)論 3 378
  • 正文 我出身青樓膘魄,卻偏偏與公主長(zhǎng)得像乌逐,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子创葡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,781評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容