Posted in Cordova/PhoneGap

[Cordova] How to download a file

cordova_logo

To download a file from given URL, we need the cordova-plugin-file-transfer plugin. You also install this plugin by command:

cordova plugin add cordova-plugin-file-transfer

Then, use below code:

 function downloadFile(downloadedFileName, downloadLink) {

var fileURL;
if (monaca.isAndroid === true) {
var androidDownloadPath = ‘/storage/emulated/0/path/to/’;
fileURL = androidDownloadPath + downloadedFileName;
} else {
var iosDownloadPath = cordova.file.documentsDirectory;
fileURL = iosDownloadPath + downloadedFileName;
}
var uri = encodeURI(downloadLink);
processDownloadFile(uri, fileURL);

}

function processDownloadFile(uri, fileURL) {
var encodedFileURL = encodeURI(fileURL);
var fileTransfer = new FileTransfer();
fileTransfer.download(
uri,
encodedFileURL,
function(entry) {
console.log(“Download complete ! Place of downloaded file: ” + entry.toURL() + ” – Source: ” + uri);
},
function(error) {
console.error(“error source ” + error.source + ” – download error target ” + error.target + ” – upload error code” + error.code);
},
false, {
headers: {
“Authorization”: “Basic false headers”
}
}
);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s