我已经阅读了很多文章,但是没有得到最终答案。从这个链接的代码开始,我已经将文件下载到应用程序中。但是,我想把它放到“下载”文件夹中。我使用的是Android,但显然我希望iOS也能使用这个解决方案。
编辑
如果您已经知道文件的路径,您可以直接移动它:
最初的回答:
var storageLocation = "";
console.log(device.platform);
switch (device.platform) {
case "Android":
storageLocation = 'file:///storage/emulated/0/';
break;
case "iOS":
storageLocation = cordova.file.documentsDirectory;
break;
}
var fileUri = "file:///data/user/0/com.arsdigitalia.myapp/files/files/MyApp/test.pdf"
function moveFile(fileUri) {
window.resolveLocalFileSystemURL(
fileUri,
function(fileEntry){
var parentEntry = storageLocation + "Download";
// move the file to a new directory and rename it
fileEntry.moveTo(parentEntry, "newFile.pdf", success, fail);
},
errorCallback);
}
最初的回答
以下是我用来实现此功能的示例代码。它在Android上表现最佳,但由于应用程序沙盒的原因,iOS略有不同,因此您需要自己处理文件的检索。我还使用Cordova设备插件来确定应用程序运行的设备,然后可以更改存储路径以适应:
var storageLocation = "";
console.log(device.platform);
switch (device.platform) {
case "Android":
storageLocation = 'file:///storage/emulated/0/';
break;
case "iOS":
storageLocation = cordova.file.documentsDirectory;
break;
}
window.resolveLocalFileSystemURL(storageLocation,
function (fileSystem) {
fileSystem.getDirectory('Download', {
create: true,
exclusive: false
},
function (directory) {
//You need to put the name you would like to use for the file here.
directory.getFile("YOUR_FILE_NAME", {
create: true,
exclusive: false
},
function (fileEntry) {
fileEntry.createWriter(function (writer) {
writer.onwriteend = function () {
console.log("File written to downloads")
};
writer.seek(0);
writer.write(YOUR_FILE_HERE); //You need to put the file, blob or base64 representation here.
}, errorCallback);
}, errorCallback);
}, errorCallback);
}, errorCallback);
var errorCallback = function(e) {
console.log("Error: " + e)
}
然后,要从目录中检索文件列表,您可以使用:
最初的回答:
dir /b
window.resolveLocalFileSystemURL(storageLocation,
function (fileSystem) {
fileSystem.getDirectory('Download', {
create: true,
exclusive: false
},
function (directory) {
var reader = directory.createReader();
reader.readEntries(function (files) {
if (files.length == 0) {
console.log("No files found in downloads folder.")
} else {
$.each(files, function (i, v) {
console.log("File Name: " + files[i].name;)
});
}
}, getFilesFail);
}, getFilesFail);
}, getFilesFail);
var getFilesFail = function(e) {
console.log("Error: " + e);
}
要安装设备插件,请使用以下命令:
cordova plugin add cordova-plugin-device
文档在这里:
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-device/
"Original Answer"翻译成"最初的回答"。
file:///storage/emulated/0/Download
吗? - João Pimentel Ferreira