Download and save image file using javascript

4,203 views
Skip to first unread message

John Kenedy

unread,
Feb 28, 2016, 6:50:17 AM2/28/16
to DroidScript
HI i am trying to download image from url and save it as file in sdcard, i write below but some device does not work

     var url2 = url; //image url

     var xhr = new XMLHttpRequest();
     xhr.responseType = "blob";
     xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200)
        {
           var blob = xhr.response;
           var arrayBuffer; 
           var fileReader = new FileReader(); 
           fileReader.onloadend = function(evt) 
           {
               if (evt.target.readyState == FileReader.DONE)
               {
                   arrayBuffer = evt.target.result;
                   var file = app.CreateFile(full, "rw"); //full = /sdcard/Anime Release/cache/1.jpg
                  
                   uint8ArrayNew = new Uint8Array(arrayBuffer);
                   file.WriteData(uint8ArrayNew, "Bytes");
                   file.Close();
              detailimage.SetImage(full, 0.3);
              }
           };
           fileReader.readAsArrayBuffer(blob);
        }
     }; 
     xhr.open("GET", url2, true); 
     xhr.send();

It works in my devices, however when I use bluestack and older xiaomi device, it does not work

Chris Hopkin

unread,
Feb 29, 2016, 7:28:26 AM2/29/16
to DroidScript
Hi  John

Do you know which bit is failing on older devices? Do you have the error messages?

It may be that FileReader is not supported on older versions of the WebView.

You might want to consider using the DroidScript Downloader instead:


Thanks

Chris

John Kenedy

unread,
Feb 29, 2016, 7:44:22 AM2/29/16
to DroidScript
Hi Chris

Most likely it is due to FileReader not working, I dont have the error message as because the file is created however it is 0 byte without error message.
I have switched to other methods using my plugin. I will try using droidscript downloader too.

Thanks
Reply all
Reply to author
Forward
0 new messages