標籤:style blog color 使用 檔案 問題
今天實現了一個檔案下載功能,在網上找了下資料發現有些問題。
我用的是小米1s,安卓 4.1.2,cordova 3.5,打包測試回合正常
首先在控制層launch方法中加入以下代碼:
1 // 等待載入PhoneGap 2 document.addEventListener("deviceready", onDeviceReady, false); 3 // PhoneGap載入完畢 4 function onDeviceReady() { 5 //尋找是否有zgky這個檔案夾,沒有則建立,然後找到這個檔案夾的絕對路徑 6 window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { 7 //util.appRootDirName 全域變數,這裡是zgky 8 fileSystem.root.getDirectory(util.appRootDirName, { 9 create: true,10 exclusive: false11 }, function (entry) {12 //網上流傳的資料中都是使用fullPath,在這裡我擷取到的是相對目錄,在下載時使用會報錯,所以換做了toURL()13 //這是一個全域全域變數,用以儲存路徑14 util.fullPath = entry.toURL();15 //console.log(‘建立檔案夾成功‘);16 //console.log(util.fullPath);17 }, function () {18 console.log(‘建立檔案夾失敗‘);19 });20 }, function () {21 console.log(‘建立檔案夾失敗‘);22 });23 }
在擷取到一個絕對路徑之後,我們就可以用一個方法來下載檔案了,方法如下,調用此方法即可下載。
1 downFile: function (url) { 2 var me = this, 3 //Regex,用於擷取檔案名稱 4 reg = /[^\\\/]*[\\\/]+/g, 5 //擷取,me.fullPath在main控制層中擷取,這是一個全域變數 6 filePath = me.fullPath + "/" + url.replace(reg, ‘‘), 7 // 8 url = encodeURI(url), 9 fileTransfer = new FileTransfer();10 console.log(‘正在下載中,請等待...‘);11 fileTransfer.download(url, filePath,12 function (entry) {13 console.log(‘下載成功!請在‘ + entry.fullPath + ‘目錄中查看‘);
15 },16 function (error) {17 console.log(‘下載失敗!‘ + error.source);
19 });20 }
在cordova中需要在建立項目時引入以下外掛程式,
::引入檔案外掛程式
cordova plugin add org.apache.cordova.file
::引入檔案管理外掛程式
cordova plugin add org.apache.cordova.file-transfer