Search code examples
cordovaxmlhttprequest

Codrova XMLHttpRequest File Download


I am working with Cordova and trying to download a file with XMLHttpRequest

I am trying to use this example

https://cordova.apache.org/blog/2017/10/18/from-filetransfer-to-xhr2.html

Here is my code

var fileName = "test.mp3";
var dlUrl = "http://myserver.com/down.php?id=123";
var fileSystem = cordova.file.externalApplicationStorageDirectory + "myfolder/downloads";

window.resolveLocalFileSystemURL(fileSystem, function (dir) {

dir.getFile(fileName, {create: true}, function (file) {

var oReq = new XMLHttpRequest();

oReq.addEventListener("progress", updateProgress);
oReq.addEventListener("load", transferComplete);
oReq.addEventListener("error", transferFailed);
oReq.addEventListener("abort", transferCanceled);

// Define how you want the XHR data to come back
oReq.responseType = "blob";

// I have added my domain to Content-Security-Policy <meta>
oReq.open("GET", dlUrl, true);

oReq.onload = function (oEvent) {

var blob = oReq.response; // Note: not oReq.responseText

if (blob) {

var url = window.URL.createObjectURL(blob);
alert( url );

} else {
alert('we didnt get an XHR response!');

};

oReq.send(null);

If I access my php download script through a browser then it will download my .mp3 file no problem. So I assume my file server script is working well.

When I run the app script Cordova will create an empty file where I want it.

The XMLHttpRequest download request runs with no errors but it doesn't actually store the fetched data in the file that Cordova creates. The file is just empty.

When I echo the URL for the blob it is not in the folder I targeted with Cordova, but rather just "file:///" and then a long string of giberish, I am assuming a temp file stored somewhere.

Question is: How do I get the downloaded data to actually be stored in the file Cordova is creating?

Thank you.


Solution

  • figured it out...

    use the following cordova function

    saveFile(file, blob);