小编典典

接收Zip文件作为对AJAX请求的响应

ajax

因此,我正在一个需要调用服务器并返回zip文件的网站上工作,问题是我不确定自己是否做对了所有事情。该代码看起来像这样:

function download(){
  if($('.download').hasClass('activeBtn')){
    $.ajax({
        type: 'GET',
        url: someUrl,
        contentType: 'application/zip',
        dataType: 'text',
        headers: {
            'Api-Version': '3.4'
        }

    }).then(function (data) {
      console.log(data); //Basically prints the byte array
      //Here I should build the file and download it
    });
  }
}

如您所见,我需要使用响应中的字节数组来填充文件,我该怎么做?


阅读 541

收藏
2020-07-26

共1个答案

小编典典

一种利用的方法XMLHttpRequest();
检查aelement是否具有download属性,如果为true,则将downloadproperty 设置为objectURL;
否则,使用window.open()带参数objectURLBlob响应

function downloadFile(url, headers, filename) {

  function handleFile(data) {
    console.log(this.response || data);
    var file = URL.createObjectURL(this.response || data);
    filename = filename || url.split("/").pop();
    var a = document.createElement("a");
    // if `a` element has `download` property
    if ("download" in a) {
      a.href = file;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    } else {
      // use `window.open()` if `download` not defined at `a` element
      window.open(file)
    }
  }

  var request = new XMLHttpRequest();
  request.responseType = "blob";
  request.onload = handleFile;
  request.open("GET", url);
  for (var prop in headers) {
    request.setRequestHeader(prop, headers[prop]);
  }

  request.send();
}

downloadFile("/path/to/resource/", {"x-content": "abc"}, "filename.zip")

使用jQuery版本jquery-ajax-blob- arraybuffer.js

/**
 *
 * jquery.binarytransport.js
 *
 * @description. jQuery ajax transport for making binary data type requests.
 * @version 1.0 
 * @author Henry Algus <henryalgus@gmail.com>
 *
 */

// use this transport for "binary" data type
$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) 
        || (options.data 
        && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) 
        || (window.Blob && options.data instanceof Blob))))
       )
    {
        return {
            // create new XMLHttpRequest
            send: function(headers, callback){
        // setup all variables
                var xhr = new XMLHttpRequest(),
        url = options.url,
        type = options.type,
        async = options.async || true,
        // blob or arraybuffer. Default is blob
        dataType = options.responseType || "blob",
        data = options.data || null,
        username = options.username || null,
        password = options.password || null;

                xhr.addEventListener('load', function(){
            var data = {};
            data[options.dataType] = xhr.response;
            // make callback and send data
            callback(xhr.status
                    , xhr.statusText
                    , data
                    , xhr.getAllResponseHeaders());
                });

                xhr.open(type, url, async, username, password);

        // setup custom headers
        for (var i in headers ) {
            xhr.setRequestHeader(i, headers[i] );
        }

                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function(){
                jqXHR.abort();
            }
        };
    }
});
function downloadFile(url, headers, filename) {
return $.ajax({
  url:url,
  dataType:"binary",
  processData: false,
  headers:headers
})
.then(function handleFile(data) {
    console.log(this.response || data);
    var file = URL.createObjectURL(this.response || data);
    filename = filename || url.split("/").pop();
    var a = document.createElement("a");
    // if `a` element has `download` property
    if ("download" in a) {
      a.href = file;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    } else {
      // use `window.open()` if `download` not defined at `a` element
      window.open(file)
    }
  })
}

downloadFile("/path/to/resource/", {"x-custom-header":"abc"}, "filename.zip");

只需下载就可以了

您可以使用<a>元素,download属性

$("<a>", {href: someUrl,
        download: "filename.zip"
}).appendTo("body")[0].click()

或者使用库解析文件,例如,从文件中包含的数据zip.js创建多个或单个可下载.zip文件。

创建每个文件的objectURL,使用a元素下载每个文件。

如果download浏览器不提供该属性,则可以使用类型设置为下载文件data URI的文件对象MIME``application/octet- stream

2020-07-26