32

I am getting below response from AJAX respose:

this is response of zip file. please let me know how to save this filename.zip in Javascript. Inside the ZIP there is PDF file.

MY code is like this:

$.ajax({

    url: baseURLDownload + "/service/report-builder/generateReportContentPDF",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
        xhr.responseType = 'arraybuffer'
    },
    type: "POST",
    data: JSON.stringify(parameter),
    contentType: "application/json",
    success: function(result) {
        console.log("ssss->"+result);
        var base64String = utf8_to_b64(result);
        //window.open("data:application/zip;base64,"+base64String); // It will download pdf in zip
        var zip = new JSZip();
        zip.add("PDFReport.pdf", result);
        content = zip.generate();
        location.href="data:application/zip;base64," + content;
        $.mobile.loading('hide');

    },
    error: function(xhr){
        console.log("Request Status: " + xhr.status + " Status Text: " + xhr.statusText + " " + xhr.responseText);
        $.mobile.loading('hide');
        showAlert("Error occured. Unable to download Report", "Message", "OK");

    }
});

RESPOSE Console.log("ssss->"+result);

PK��Q��F���������������/crt_pdf_10204725.pdf��uX\M�8|p�����݃�;w�@p �ܝBp��݂�;|C�ھ�w������=O���]]�%�N�����#+�reup����������Y������̉�J����3)� O��C����F�M�P�&�����rA�@��7T.��z(%h��x�x0�0Z�-i��%q�e�M�����i�"�c��-/��j��齔/ļL瞄�0� �� >�o��[��6 멆�n��s�$� �#>˘ '��wT�� ���3�36DK�+�̓�t6 ��r��sA:���x�<>n������'U��RLqA+���ݺ�BM��:4ĞP�}���:�}ߣP����?F)�9-�W0���2�{x��#2v8N.$V�>X=/�+�c}���ּ�\y���\*�J\�� ���90�T�L� 3p���*Sfj(���PWWz��O�s�9]&����iO|�9�;�5��ʘdW�cl% �%;����u���%[�5������Q]$��[L>���yXg�9��2+&,iFs�Q�����u�.�E(�>W��+��M ؟E������i|���k�k�c蟴CcG�j��4s|x �F1�}��Y��,29�0M=-O����m\L��y��^On^���\���u��a���F9:zc�Sy�-�g��fu�n�C�T:{ ��4&/ ��LM9�98� �&Pnc�!��m�r�~��)74�04��0�0������M�~"��.ikjG��M�-

Robert Harvey
  • 173,679
  • 45
  • 326
  • 490
Nishant Singh
  • 649
  • 1
  • 6
  • 7

6 Answers6

32

Finally I got answer of my question:

Here is the code:

var xhr = new XMLHttpRequest();
xhr.open("POST", baseURLDownload + "/service/report/QCPReport", true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        // alert("Failed to download:" + xhr.status + "---" + xhr.statusText);
        var blob = new Blob([xhr.response], {type: "octet/stream"});
        var fileName = "QCPReport.zip";
        saveAs(blob, fileName);
    }
}
xhr.responseType = "arraybuffer";
xhr.send(JSON.stringify(QCPParameter));
Alessio Cantarella
  • 4,800
  • 3
  • 26
  • 31
Nishant Singh
  • 649
  • 1
  • 6
  • 7
13

No dependancy.

Compatible with IE 10,11, Chrome, FF and Safari:

function str2bytes (str) {
   var bytes = new Uint8Array(str.length);
   for (var i=0; i<str.length; i++) {
      bytes[i] = str.charCodeAt(i);
    }
    return bytes;
}

var xhr = new XMLHttpRequest();
xhr.open("POST", baseURLDownload + "/service/report/QCPReport", true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        // alert("Failed to download:" + xhr.status + "---" + xhr.statusText);
        var blob = new Blob([str2bytes(xhr.response)], {type: "application/zip"});
        var fileName = "QCPReport.zip";
        if (navigator.msSaveOrOpenBlob) {
            navigator.msSaveOrOpenBlob(blob, filename);
        } else {
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.style = "display:none";
            var url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
            a.remove();
        }
    }
}
xhr.responseType = "arraybuffer";
xhr.send(JSON.stringify(QCPParameter));
Below the Radar
  • 6,947
  • 10
  • 58
  • 131
  • This worked for me, thank you! I just had to remove the call to the `str2bytes` function. – Xar Nov 05 '21 at 14:34
8

Axios implementation:

const url = 'https://www.example.com/download-zip'

// Payload, eg list of docs to zip
const payload = { documents: ['id1', 'id2', 'id3'] }

// Axios options
const axiosOptions = {
  responseType: 'arraybuffer',
  headers: {
    'Content-Type': 'application/json'
  }
}

// Fetch data and save file
axios
  .post(url, payload, axiosOptions)
  .then((response) => {
    const blob = new Blob([response.data], {
      type: 'application/octet-stream'
    })
    const filename = 'download.zip'
    saveAs(blob, filename)
  })
  .catch((e) => {
    // Handle error
  })
})

Note

saveAs is a function from file-saver package I've been using to handle saving the file.

ego
  • 3,765
  • 1
  • 34
  • 36
  • 1
    Where does the saveAs function come from? – Ashwin Feb 02 '22 at 16:39
  • @Ashwin Either helper function or a package implementation for saving the file. Most likely I was using `file-saver`: https://www.npmjs.com/package/file-saver – ego Feb 03 '22 at 14:18
2

For those of you using fetch, you can do this doing something like this.

fetch(url, config).
  .then((response) => {
    return response.arrayBuffer()
  })
  .then((data) => handleData(data))

In handleData, you will then instantiate the Blob object to handle the zip data.

IonicBurger
  • 4,663
  • 1
  • 38
  • 46
0

Here is my Answer you can avoid using blob and avoid using Filesaver.

This is how i wrote for one of my project using GET Method

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
xmlHttp.setRequestHeader("Content-type","application/json");
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.responseType= 'blob';

xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        const downloadUrl = window.URL.createObjectURL(xmlHttp.response);
        const link = document.createElement('a');
        link.setAttribute('href', downloadUrl);
        link.setAttribute('download', `filename.zip`);
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
    }
}
xmlHttp.responseType = "arraybuffer";
xmlHttp.send();
-1

There are libraries (zip.js comes to mind) for handling this sort of thing, assuming you want to get at what is in the zip file. If you just want to save the zip file, you would treat it like any other file.

Scott Hunter
  • 46,905
  • 10
  • 55
  • 92