我试图将远程文件下载到我的设备。 我正在使用PhoneGap Build。这是我的代码。
我尝试了我发现的每一段代码。当我点击下载按钮时,没有任何反应。在调试时,不会出现任何错误。
我在哪里弄错了?
<script type="text/javascript">
window.appRootDirName = "my_app";
function onLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
console.log("device is ready");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
console.log("filesystem got");
window.fileSystem = fileSystem;
fileSystem.root.getDirectory(window.appRootDirName, {
create : true,
exclusive : false
}, dirReady, fail);
}
function dirReady(entry) {
window.appRootDir = entry;
console.log('application dir is ready');
}
function fail() {
console.log('failed to get filesystem');
}
function downloadFile(url,fileName) {
var fileTransfer = new FileTransfer();
var filePath = window.appRootDir.fullPath + "/" + fileName + ".txt";
fileTransfer.download(url, filePath, function(entry) {
alert("download complete: " + entry.fullPath);
}, function(error) {
console.log(error);
});
}
$(document).ready(function(){
.... some other code
//on click download file
$(document).on('click touchstart', '.download', function(e){
e && e.preventDefault();
var url = $(this).data('url');
var title = $(this).data('title');
downloadFile(url,title);
});
});
</script>
还有config.xml
<gap:plugin name="com.coconutcenter.file-transfer" version="0.4.6" />
<feature name="http://api.phonegap.com/1.0/file" />
<feature name="File">
<param name="android-package" value="org.apache.cordova.file.FileUtils" />
</feature>
<feature name="FileTransfer">
<param name="android-package" value="org.apache.cordova.filetransfer.FileTransfer" />
</feature>
<feature name="Storage">
<param value="org.apache.cordova.Storage" name="android-package"/>
</feature>
.download方法的错误代码:
{"code":1,"source":"http://myurl.com/file.txt","target":"//my_app/file.txt","http_status":null,"body":null}
最后我找到了解决方案。如上所述here,我使用了.toUrl()
insetad fullPath
。所以我的downloadFile函数将是;
function downloadFile(url,fileName) {
var fileTransfer = new FileTransfer();
var filePath = window.appRootDir.toUrl() + "/" + fileName + ".txt"; //here
fileTransfer.download(url, filePath, function(entry) {
alert("download complete: " + entry.fullPath);
}, function(error) {
console.log(error);
});
}
答案 0 :(得分:0)
最后我找到了解决方案。如上所述[{3}},我使用.toUrl()
代替fullPath