0

I use cordova with file plugin. I tried many solutions from different forums and none seems to be working.

<!DOCTYPE html>
<html>
    <head>
        <title>aaa</title>
        <script src="js.js"></script>
    </head>
    <body>
            <span onclick="testDownload()">click</span>
    </body>
</html>

this is from: https://stackoverflow.com/a/53083810/16003367

function DownloadToDevice(fileurl) {
  var blob = null;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", fileurl);
  xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
  xhr.onload = function()
  {
      blob = xhr.response;//xhr.response is now a blob object
      console.log(blob);
      var storageLocation = "";
//     switch (device.platform) {
//         case "Android":
             storageLocation = 'file:///storage/emulated/0/';
//             break;
//         case "iOS":
//             storageLocation = cordova.file.documentsDirectory;
//             break;
//     }
     var folderpath = storageLocation + "Download";
     var filename = "Myimg.png";
     var DataBlob = blob;
      window.resolveLocalFileSystemURL(folderpath, function(dir) {
        dir.getFile(filename, {create:true}, function(file) {
                file.createWriter(function(fileWriter) {
                    fileWriter.write(DataBlob);
                    //Download was succesfull
                }, function(err){
                  // failed
                  console.log(err);
                });
        });
      });
  };
  xhr.send();
}


function testDownload() {
    DownloadToDevice('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSPkOcqTJH4tkT_Zlit1poKuS9TPWNylC7qg&usqp=CAU');
}

my config file:

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.hello.aaaa" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>aaa</name>
    <description>Sample Apache Cordova App</description>
    <author email="dev@cordova.apache.org" href="https://cordova.apache.org">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <preference name="AndroidPersistentFileLocation" value="Compatibility" />
    <preference name="AndroidExtraFilesystems" value="files,cache, sdcard, cache-external, files-external" />

    <edit-config file="AndroidManifest.xml" target="/manifest/uses-sdk" mode="merge">
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    </edit-config>
</widget>

I'm testing in android studio emulator. This is not network problem, because downloading random file from browser works. I granted permissions in settings -> app settings -> myapp -> app permissions

enter image description here enter image description here

And nothing happens when I press the button. What am I missing? Please help

m1212
  • 31
  • 6

1 Answers1

1

I used this to download images :

function imageExists(image_url){

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {

    //console.log('file system open: ' + fs.name);
    getSampleFile(fs.root, image_url);

}, onErrorRequestFS);

return true;

}

function getSampleFile(dirEntry, image_url) {

//window.resolveLocalFileSystemURL("file:///android_asset/www/img/" + image_url, fileExists, 
//window.resolveLocalFileSystemURL(cordova.file.dataDirectory + image_url, fileExists, 
window.resolveLocalFileSystemURL(dirEntry.nativeURL + image_url, fileExists, 

    function () { 
    
        var xhr = new XMLHttpRequest();
        xhr.open('GET', "https://www.mondomain.com/" + image_url, true);
        xhr.responseType = 'blob';

        xhr.onload = function() {
            if (this.status == 200) {
                //console.log("file exists on server : " + JSON.stringify(dirEntry) + image_url);
                var blob = new Blob([this.response], { type: 'image/png' });
                
                saveFile(dirEntry, blob, image_url);
            }
            else {
                console.log("file not exists on server : " + this.status);
            }
        };
        xhr.send();
    }   
);

}

function saveFile(dirEntry, fileData, fileName) {

dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
    
    writeFile(fileEntry, fileData);
    
}, onErrorSaveFileFS);

}

function writeFile(fileEntry, dataObj, isAppend) {

fileEntry.createWriter(function (fileWriter) {

    fileWriter.onwriteend = function() {
        //console.log("Successful file write...");
        /*if (dataObj.type == "image/png") {
            readBinaryFile(fileEntry);
        }
        else {
            readFile(fileEntry);
        }*/
    };

    fileWriter.onerror = function(e) {
        console.log("Failed file write: " + e.toString());
    };

    fileWriter.write(dataObj);
});

}

function onErrorRequestFS(err) {
    console.log("File onErrorRequestFS" + err.code);
}

function onErrorSaveFileFS(err) {
    console.log("File onErrorSaveFileFS" + err.code);
}
Ben
  • 11
  • 4
  • Thank you for your answer. Unfortunatly my file isn't downloaded from server but generated by app (as string, and i want to make it .txt), but I try to change your code, tho I dont think I'm able to.. Also: how saveFile function works? – m1212 Oct 14 '22 at 15:22
  • This is my text to create blob: async function generateTxt(text) { // text is string var textFile = null; var data = new Blob([text], { type: 'text/plain' }); if (textFile !== null) { window.URL.revokeObjectURL(textFile); } textFile = window.URL.createObjectURL(data); return textFile; //returns blob How could I fit it into Your code? On browser I simply make link.href = await generateTxt(dataString) and when i click on the link file opens or downloads. But I cant make it on android, i've been trying for like 2 weeks now......... – m1212 Oct 14 '22 at 15:31
  • I edit my post. I found this code for downloading automatically new icons in my app to device. – Ben Oct 15 '22 at 03:49
  • Have you found solutions ? – Ben Oct 21 '22 at 04:00