Nishant Singh
Nishant Singh

Reputation: 768

How to save binary data of zip file in Javascript?

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�-

Upvotes: 39

Views: 96238

Answers (5)

Be Kind
Be Kind

Reputation: 5172

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.

Upvotes: 18

Vishal Dindalkop
Vishal Dindalkop

Reputation: 17

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();

Upvotes: -1

JackDev
JackDev

Reputation: 5072

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.

Upvotes: 2

Below the Radar
Below the Radar

Reputation: 7635

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));

Upvotes: 14

Nishant Singh
Nishant Singh

Reputation: 768

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));

Upvotes: 37

Related Questions