<!-- 打包的时候phonegap自己会添加这个文件--> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <!-- <script type="text/javascript" charset="utf-8" src="js/FileTransfer.js"></script> --> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // document.addEventListener("deviceready",onDeviceReady,false); // device APIs are available // function onDeviceReady() { alert('onDeviceReady2222'); try { /* window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.ebkitResolveLocalFileSystemURL; //根据URL取得文件的读取权限 */ //查找是否有download这个文件夹,没有则创建,然后找到这个文件夹的绝对路径 window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getDirectory("download", { create: true, exclusive: false }, function (entry) { //网上流传的资料中都是使用fullPath,在这里我获取到的是相对目录,在下载时使用会报错,所以换做了toURL() //这是一个全局全局变量,用以保存路径 fullPath = entry.toURL(); alert(fullPath.toString() + '创建文件夹成功'); //console.log(fullPath); }, function () { console.log('创建文件夹失败'); alert('创建文件夹失败'); }); }, function () { console.log('创建文件夹失败'); alert('创建文件夹失败'); }); } catch (e) { alert(e.name + ":" + e.message); } }
function downloadFile() { alert(androidFile); try { // onDeviceReady(); var ft = new FileTransfer(); var uri = encodeURI(androidFile); var fileURL = fullPath + androidFile.substr(androidFile.lastIndexOf('/') + 1); alert("准备下载"+fileURL); ft.download( uri, fileURL, function(entry) { OpenFile(entry.fullPath); console.log("download complete: " + entry.toURL()); }, function(error) { alert("download error source " + error.source); alert("download error target " + error.target); console.log("download error source " + error.source); console.log("download error target " + error.target); console.log("upload error code" + error.code); }, false, { headers: { "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" } } ); } catch (e) { alert(e.name + ":" + e.message); } }
<div> <a id="androidurl" href="#" onclick="downloadFile();return false;"><img class="productImg" src="res/android.png" alt="ANDROID" width="80px" height="80px" />Android版</a> </div>
前提是安装插件:
cordova create my-app
cd my-app
cd plugin
cordova plugin add org.apache.cordova.file-transfer
cordova plugin add org.apache.cordova.file
cordova build android
测试版本是cordova 4.1.2