2016-07-04 175 views
1

因此,我正在开发一个需要对服务器进行调用并返回一个zip文件的网站,事情是我并不确定自己正在做什么一切都正确。代码看起来有点像这样:在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 
    }); 
    } 
} 

正如你看到的,我需要化妆用字节数组是在响应文件,我该怎么办呢?

+0

你有什么计划在JavaScript中的zip文件?你想让用户下载它吗?或者你想用Javascript来操纵它? – DutchKevv

+0

@DutchKev只需要下载它,这就是所有 –

回答

1

利用XMLHttpRequest()的方法;检查a元素是否具有download属性,如果属实,则将download属性设置为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的版本使用forkjquery-ajax-blob-arraybuffer.js

/** 
* 
* jquery.binarytransport.js 
* 
* @description. jQuery ajax transport for making binary data type requests. 
* @version 1.0 
* @author Henry Algus <[email protected]> 
* 
*/ 

// 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 URIMIME类型设置为application/octet-stream下载文件

+1

请注意'下载'仍然存在跨浏览器支持问题http://caniuse.com/#feat=download – charlietfl

+1

@charlietfl是的,包括使用'data URI'的替代方法的描述,'application/octet-stream'下载文件,如果'download'属性在浏览器中不可用 – guest271314

+0

@ guest271314好的,我忘了指定我发送一些自定义标题,所以是的,我的坏。任何想法? –