欢迎访问 夜阑小雨 我的学习碎片档案,这里记录了我的学习内容和工作中经验,希望给您带去帮助。

Cordova 3.x下载文件-phonegap3.x文件下载

Android开发 夜阑小雨 2470℃

在cordova3.5中需要在创建项目时引入以下插件,

::引入文件插件
cordova plugin add org.apache.cordova.file
::引入文件管理插件
cordova plugin add org.apache.cordova.file-transfer

js代码:
// 等待加载PhoneGap
document.addEventListener(“deviceready”, onDeviceReady, false);

function onDeviceReady() {

window.fullPath; //全局变保存文件的路径
fileReady();

}

//创建目录
function fileReady() {
console.log(“device is ready”);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
//download_pic 是创建的文件夹
fileSystem.root.getDirectory(“download_pic”, {
create: true,
exclusive: false
}, function (entry) {
//网上流传的资料中都是使用fullPath,在这里我获取到的是相对目录,在下载时使用会报错,所以换做了toURL()
//这是一个全局全局变量,用以保存路径
window.fullPath = entry.toURL();

}, function () {
console.log(‘创建文件夹失败’);
console.log(window.fullPath);
});
}, function () {
console.log(‘创建文件夹失败’);
});
}

//下载方法
function downloadFile(url){
reg = /[^\\\/]*[\\\/]+/g;
filePath = window.fullPath + “/” + url.replace(reg, ”);
url = encodeURI(url),
fileTransfer = new FileTransfer();
$.ui.showMask(“正在保存…”);
fileTransfer.download(url, filePath,
function (entry) {
$.ui.hideMask();
showalert(‘保存成功!请在’ + window.fullPath + ‘目录中查看’);
console.log(“download complete: ” + entry.fullPath);
console.log(“download name: ” + entry.name);

},
function (error) {
showalert(“保存失败!”);
/*showalert(“error”);
showalert(JSON.stringify(error));*/
console.log(“download error source ” + error.source);
console.log(“download error target ” + error.target);
console.log(“upload error code” + error.code);
});

}

<li><a href=”javascript:downloadFile(‘http://www.yeeyi.com/bbs/data/attachment/forum/mobile/1830133_app_164305rzordz5d51rw5ovr.jpg’);”><img src=’images/icon/save.png’/></a></li>

转载请注明:夜阑小雨 » Cordova 3.x下载文件-phonegap3.x文件下载

喜欢 (0)or分享 (0)