用jquery从ajax post请求下载zip文件


Download zip file with jquery from ajax post request

我想知道是否有可能对特定url进行ajax post请求,并仅在请求时接收数据中的zip文件?或者我必须发送两个请求……一个是为了在已经创建的服务器中拥有zip文件的url,另一个是下载zip文件?

你当然可以做到!但只有新浏览器才支持。

var url = 'test.zip';
var filename = 'test.zip';
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'blob';
request.onload = function() {
   var link = document.createElement('a');
   document.body.appendChild(link);
   link.href = window.URL.createObjectURL(request.response);
   link.download = filename;
   link.click();
};
request.send();

答案是否定的!

但是你可以这样做。

ajax请求:

$.ajax({
    url: 'your-url-that-gives-zip-file.php',
    dataType: 'JSON',
    success: function(response){
        if(response.zip) {
            location.href = response.zip;
        }
    }
});

你的php文件

<?php
//Get your zip file code with and combine with http://youradress.com
$zipFile = 'http://youraddress.com/downloads/'.$zipFile;
echo json_encode(array('zip' => $zipFile));
?>

你不能用ajax下载文件。

如果您只想要一个请求,那么放弃ajax并将一个隐藏的iframe附加到页面,并将php文件作为其源文件。

这将限制您的get请求。

,

$('#id').click(function(){
    $(body).append('<iframe style="display:none;" src="yourfile.php?key=value"></iframe>');
});