Cordova - Download file to download folder
1 answer
EDIT
If you already know the path to the file, you can simply move it:
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);
}
Original
Here is some sample code I am using for this. It works best on Android, iOS is slightly different due to the app sandbox, so you have to handle the file extraction yourself. I am also using the Cordova device plugin to determine which device the application is running on. Then I can change the storage paths to match:
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)
}
Then, to get a list of files from a directory, you can use:
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);
}
Use the following command to install the device plugin:
cordova plugin add cordova-plugin-device
Documentation here:
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-device/
+5
source to share