简体   繁体   English

无法将八位字节流的响应数据转换为 Zip 文件并下载

[英]Unable to convert response data of octet-stream to Zip file and download it

I am trying to download Zip file containing JSON files from AJAX GET Request.我正在尝试从 AJAX GET 请求下载包含 JSON 文件的 Zip 文件。

Response Headers format:响应头格式:

Connection: keep-alive
content-disposition: attachment;filename=exportedFiles_ 1.6.0_20200731160652.zip
Content-Length: 4496
Content-Type: application/octet-stream
Date: Fri, 31 Jul 2020 10:36:52 GMT

Data Preview in Network Tab:网络选项卡中的数据预览:

在此处输入图像描述

AJAX call and success function: AJAX 调用并成功 function:

$.ajax({
      type: "GET",
      url: "/download/" ,
      async: false,
      success: function (data,status, xhr) {          
      var filename = xhr.getResponseHeader('content-disposition').split("filename=")[1];;
      var blob = new Blob([data], {type: "octet/stream"})
       saveAs(blob, filename); 
      }
    });

Its saving the Zip file but when I try to open the Zip file it says " Windows cannot open the folder, The compressed Zip is invalid ".它保存了 Zip 文件,但是当我尝试打开 Zip 文件时,它显示“ Windows 无法打开文件夹,压缩后的 Z963AB0BBEA2F1B14D19 无效”。

在此处输入图像描述

Implement an Axios handler for the Received document, the data format octect-stream , data might look weird PK something JbxfFGvddvbdfbVVH34365436fdkln as its octet stream format, you might end up creating file with this data might be corrupt, {responseType: 'blob'} will make data into readable format, Implement an Axios handler for the Received document, the data format octect-stream , data might look weird PK something JbxfFGvddvbdfbVVH34365436fdkln as its octet stream format, you might end up creating file with this data might be corrupt, {responseType: 'blob'} will将数据转换为可读格式,

axios.get("URL", {responseType: 'blob'})
     .then((r) => {
         let fileName =  r.headers['content-disposition'].split('filename=')[1];
         let blob = new Blob([r.data]);
         window.saveAs(blob, fileName);             
      }).catch(err => {
        console.log(err);
      });

you might have tried solution which fails like this, window.saveAs(blob, 'file.zip') will try to save file as zip but will wont work,您可能已经尝试过像这样失败的解决方案, window.saveAs(blob, 'file.zip')将尝试将文件另存为 zip 但不会工作,

const downloadFile = (fileData) => {
    axios.get(baseUrl+"/file/download/"+fileData.id)
        .then((response) => {
            console.log(response.data);
            const blob = new Blob([response.data], {type: response.headers['content-type'], encoding:'UTF-8'});
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = 'file.zip';
            link.click();
        })
        .catch((err) => console.log(err))
}
const downloadFile = (fileData) => {
axios.get(baseUrl+"/file/download/"+fileData.id)
    .then((response) => {
        console.log(response);
        //const binaryString = window.atob(response.data)
        //const bytes = new Uint8Array(response.data)
        //const arrBuff = bytes.map((byte, i) => response.data.charCodeAt(i));
        //var base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(response.data)));
        const blob = new Blob([response.data], {type:"application/octet-stream"});
        window.saveAs(blob, 'file.zip')
        // const link = document.createElement('a');
        // link.href = window.URL.createObjectURL(blob);
        // link.download = 'file.zip';
        // link.click();
    })
    .catch((err) => console.log(err))
}
function base64ToArrayBuffer(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    };

    return bytes;
}

another short solution is,另一个简短的解决方案是,

window.open("URL")

will keep opening new tabs unnecessarily and user might have to make allow popups for work this code, what if user want to download multiple files at the same time so go with solution first or if not try for other solutions also将继续不必要地打开新标签,用户可能必须allow popups才能工作此代码,如果用户想同时下载多个文件,那么 go 首先使用解决方案,或者如果不尝试其他解决方案也

Set the response type to arraybuffer:将响应类型设置为 arraybuffer:

dataType: 'arraybuffer'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM