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

标签 javascript jquery ajax http zip

所以我在一个需要调用服务器的网站上工作,它返回一个 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
    });
  }
}

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

最佳答案

利用 XMLHttpRequest() 的方法;检查是否a元素有 download属性,如果为真,则设置 download objectURL 的属性(property);否则,使用 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 版本使用 fork 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");

Just have to download it, that's all

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

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

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

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

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

关于javascript - 接收 Zip 文件作为对 AJAX 请求的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38192854/

相关文章:

javascript - 在 PHP 中调用自定义 JS 警报

javascript - 检查数组的所有值是否相等

javascript - 使用Promises的BrowserWindow.capturePage()示例?

JqueryUI : trying to show a dialog

javascript - JQuery UI 拖放而不拖放

javascript - jQuery Spritely 插件不适用于 jQuery + 1.11

javascript - 如何在angularjs中调用 Controller 内的javascript函数

javascript - 单击多个链接时如何从 session 中获取先前的链接值

jquery - 如何将 jQuery 表单提交转换为 Ajax?

javascript - 如何使用ajax将文件发送到另一个php文件后返回文件信息