程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了接收Zip文件作为对AJAX请求的响应大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决接收Zip文件作为对AJAX请求的响应?

开发过程中遇到接收Zip文件作为对AJAX请求的响应的问题如何解决?下面主要结合日常开发的经验,给出你关于接收Zip文件作为对AJAX请求的响应的解决方法建议,希望对你解决接收Zip文件作为对AJAX请求的响应有所启发或帮助;

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

function downloadfile(url, headers, file@R_419_6889@) {

  function handlefile(data) {
    console.log(this.response || data);
    var file = URl.createObjectURL(this.response || data);
    file@R_419_6889@ = file@R_419_6889@ || url.split("/").pop();
    var a = document.createElement("a");
    // if `a` element has `download` property
    if ("download" in a) {
      a.href = file;
      a.download = file@R_419_6889@;
      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"}, "file@R_419_6889@.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,
        user@R_419_6889@ = optionS.User@R_419_6889@ || 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, user@R_419_6889@, 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, file@R_419_6889@) {
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);
    file@R_419_6889@ = file@R_419_6889@ || url.split("/").pop();
    var a = document.createElement("a");
    // if `a` element has `download` property
    if ("download" in a) {
      a.href = file;
      a.download = file@R_419_6889@;
      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"}, "file@R_419_6889@.zip");

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

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

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

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

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

解决方法

因此,我正在一个需要调用服务器并返回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
    });
  }
}

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

大佬总结

以上是大佬教程为你收集整理的接收Zip文件作为对AJAX请求的响应全部内容,希望文章能够帮你解决接收Zip文件作为对AJAX请求的响应所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。