File download plugin

163 views
Skip to first unread message

Nii Darko Darkoh

unread,
Jul 7, 2022, 7:40:33 PM7/7/22
to DroidScript
Hi guys,
Does anyone know of a plugin or code for downloading a file in javascript?

I want code to download a file from a external source into private folder.

I have tried the cordova-pligin-file-transfer plugin but doesn't work.

This failure causes the fileTransfer class to also fail.

I want this code to download a file in iOS since we are still waiting for the enjine.io setup.

Can anyone help?
Thanks in advance.

Right2TheV0id

unread,
Jul 7, 2022, 8:42:02 PM7/7/22
to DroidScript
Not sure to get what you mean while talking about "ios" and "cordova plugin".
But as you are on the DroidScript forum, all I can do is to point you those two functions:

Nii Darko Darkoh

unread,
Jul 8, 2022, 5:17:14 AM7/8/22
to DroidScript
Hi Right2TheV0id,
Thanks for the effort. What you gave me is DS codes for file download.
I already have that and it works in my Android apps. What I am looking for is pure javascript code 
for file download. I have some but they all employ the FILETRANSFER code that
is no more compatible with modern devices.
Even if you use the cordova-pligin-file-transfer plugin, it fails.

So I started looking into nodejs but...
So I am wondering if anyone has  pure JS code for file download that works.
Thanks all.
-Nii

Symbroson

unread,
Jul 8, 2022, 5:39:35 AM7/8/22
to DroidScript

Nii Darko Darkoh

unread,
Jul 10, 2022, 9:38:50 AM7/10/22
to DroidScript
Hi Symbrosson, thanks for pointing me in a good direction.
I was able to come up with some codes but just can't get 
it to download a file. Can you please inspect to see what I may be 
doing wrong in my code? Code is below.
Thanks.
-Nii
---------------
// This code downloads a file
 function downloadfile_ds(SourceFileURL, FileToDownld, DestFolder, DestFileName, displayfilename) {
        try{  
            //alert('111111'); 
            //cordova.file.applicationDirectory + "pl/foldername"; //"///storage/ emulated/0/DCIM/myFile";
            var SaveDestFileAs = DestFolder+ DestFileName; 
            ShowSnackbar( "Download started. "+ FileToDownld); 
            //var fileName = 'pdf.pdf';
            var xhr = new XMLHttpRequest();
            xhr.onprogress = function(pe) {
                console.log('progress');
                if (pe.lengthComputable) {
                    ShowSnackbar((pe.loaded / pe.total) * 100);
                } 
            };
            xhr.onload = function(e) {
                if (this.status == 200) {
                    alert('loaded..');
                    var blob = this.response;
                    //var blobUrl = window.URL.createObjectURL(new Blob([blob], {type: blob.type}));
                    var blobobj = new Blob([blob], {type: blob.type});
                    writeFile(blobobj, DestFileName);
                    ShowSnackbar("Completed: " + displayfilename );
                    loadlibrary();
                    loader('hide'); 
                    return DestFolder + "/" + FileToDownld;
                }
            };
            /*xhr.onerror= function(err){
                ShowSnackbar("Error: " + err.toString() + " " + displayfilename );
                loadlibrary();
                loader('hide');
            };*/
         xhr.onreadystatechange = function(){ 
         if(this.readyState == 4 && this.status == 200) { 
             alert('this.responseText ..'+this.responseText);
                loader('hide');
                loadlibrary();               
                return;
            }};                        
            //alert(' SourceFileURL '+ SourceFileURL);
            xhr.open("get", SourceFileURL, true);
            //xhr.overrideMimeType('text/plain; charset=x-user-defined');
            xhr.overrideMimeType("application/octet-stream");
            //xhr.responseType = "blob";  
            xhr.responseType = "arraybuffer";  
   //xhr.onerror=errorFunc;  
   xhr.timeout=25000;
            xhr.send(); 
            alert('444444'); 
            //return; 
        }catch (e) {
            alert("Error "+ e ); 
            loader("hide");  
            return; 
        } 
 } 

    //Code for writing file 
    function writeFile(blob, fileName) {
        //var type = window.TEMPORARY;
        //var size = 5*1024*1024;
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, successCallback, errorCallback);
        function successCallback(fs) {
            fs.root.getFile(fileName, {create: true}, function(fileEntry) {
                fileEntry.createWriter(function(fileWriter) {
                    fileWriter.onwriteend = function(e) {
                        //alert('Write completed.'); 
                    };
                    fileWriter.onerror = function(e) {  
                        //alert('Write failed: ' + e.toString());
                    };
                    //var blob = new Blob(["Lorem Ipsum"], {type: "text/plain"});
                    fileWriter.write(blob);
                }, errorCallback);
            }, errorCallback);
        }
        function errorCallback(error) {
            alert("ERROR: " + error.code)

Symbroson

unread,
Sep 2, 2022, 10:57:39 AM9/2/22
to DroidScript
Tested this with DS methids and it seemed to work just fine - the downloaded image could be displayed in the gallery too
note: I made use of the File object to save the byte data


//Called when application is started.
function OnStart()
{
   file =
      "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedi...@2x.png";
   dest = "logo.png";
   downloadfile_ds(file, dest);

}

// This code downloads a file
function downloadfile_ds(SourceFileURL, dest)
{
   try
   {
      app.ShowProgressBar("Download started");


      //var fileName = 'pdf.pdf';
      var xhr = new XMLHttpRequest();
      xhr.onprogress = function(pe)
      {
         if(pe.lengthComputable)
            app.UpdateProgressBar((pe.loaded / pe.total) * 100);

      };

      xhr.onload = function(e)
      {
         if(this.status == 200)
         {
            var bytes = [...new Uint8Array(this.response)];
            file = app.CreateFile(dest, "rw");
            file.WriteData(bytes, "bytes");
            file.Close();
            app.ShowPopup("done")

         }
      };
      /*xhr.onerror= function(err){
          ShowSnackbar("Error: " + err.toString() + " " + displayfilename );
          loadlibrary();
          loader('hide');
      };*/
      xhr.onreadystatechange = function()
      {
         if(this.readyState == 4 && this.status == 200)
            app.HideProgressBar()

      };
      xhr.open("get", SourceFileURL, true);
      xhr.responseType = "arraybuffer";
      xhr.timeout = 25000;
      xhr.send();
   }
   catch(e)
   {
      alert("Error " + e);
      app.HideProgressBar()
      return;
Reply all
Reply to author
Forward
0 new messages