如何在Javascript中保存zip文件的二进制数据?

时间:2015-06-30 00:53:09

标签: javascript binary zip

我收到了来自AJAX respose的响应:

这是zip文件的响应。 请告诉我如何在Javascript中保存这个filename.zip。在ZIP中有PDF文件。

我的代码是这样的:

$.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 Con​​sole.log(“ssss->”+结果);

PKQF / crt_pdf_10204725.pdfuX \ M8 | P݃; W @表示P ܝBP݂; | Cھ瓦特= O]]%N#+ reupY ̉ J 3) O C F M P &amp; rA @ 7T. z(%h x x0 0Z -i %q e M i “ c -/ j /ļL瞄 &gt ; 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&gt; yXg 9 2+&amp;,iFs Q u . E( &gt; W + M?E I | ���k�k�c蟴CcG�j��4s|x �F 1} Y,290M = -Om \ Ly的^论^ \ uaF9:zcSy-gfunCT:{ 4安培/ LM998 &安培;!了Pnc先生〜)740400M〜” .ikjGM-

6 个答案:

答案 0 :(得分:19)

最后我回答了我的问题:

以下是代码:

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

答案 1 :(得分:3)

没有依赖性。

兼容IE 10,11,Chrome,FF和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));

答案 2 :(得分:1)

Axios实现:

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

答案 3 :(得分:0)

有一些库(zip.js可以想到)用于处理这类事情,假设您想要获取zip文件中的内容。如果您只想保存zip文件,则可以将其视为任何其他文件。

答案 4 :(得分:0)

对于使用fetch的用户,您可以执行以下操作。

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

然后在handleData中,实例化Blob对象以处理zip数据。

答案 5 :(得分:0)

这是我的答案 您可以避免使用blob并避免使用Filesaver。

这就是我使用GET方法为我的一个项目写的方式

RewriteCond %{QUERY_STRING} !(?:^|&)cat=[a-z](?:&|$) [NC]
RewriteRule ^ - [F]