0

I tried to download a zipfile from a webserver programatically using javascript- and am facing challenges with the archive getting corrupted.

I am using the following function to download

function download(){
        var http = new XMLHttpRequest();
        http.open("GET", 'http://jadonchemicals.com/sample.zip');
        http.setRequestHeader("dataType", "jsonp");
        http.onreadystatechange = function () {
             if (http.readyState == 4 && http.status == 200) 
             {
              var blobdata=new Blob([http.responseText], {type:  "application/zip"});
             var a = document.createElement("a");
             a.href = window.URL.createObjectURL(blobdata);
             a.click();
             }
         };
            http.send();
}

I get the following errors when I try to open the archive

a) The file header is corrupt
b) unexpected end of archive

As an example, while downloading the sample.zip file on this link, the file does get downloaded to a size of 975k. http://jadonchemicals.com/Blobtozip/

When I try to do the same programatically using javascript by linking the script to a button, the file size increases to 1779k and the file is corrupted

I suspect this is a result of an encoding issue. Could you suggest what I should do to resolve?

user7995357
  • 151
  • 10

1 Answers1

0

You can download a file in javascript like this:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
    document.getElementById('my_iframe').src = url;
};
Download("http://jadonchemicals.com/sample.zip")
</script>

You just need to insert the code into your html document. I have tried downloading your specified file using this and it was the correct 975KB and was not corrupt.

0liveradam8
  • 752
  • 4
  • 18
  • thanks @0liveradam8... I missed mentioning a critical part of the need. We also need to send the file to a cloud server and hence looking to form the file in LocalStorage from the blob. if I download, I cannot do this automatically. Building the file is causing the corruption – user7995357 Aug 20 '17 at 03:39
  • Perhaps this post https://stackoverflow.com/questions/21008732/javascript-save-blob-to-localstorage can help you save blob to localStorage. – 0liveradam8 Aug 20 '17 at 09:52