从ajax post请求下载带有jquery的zip文件

时间:2014-05-15 11:20:51

标签: php jquery ajax

我想知道是否可以对特定网址发送ajax发布请求,并仅在请求时接收数据中的zip文件?或者我必须发送两个请求...一个,为了将zip文件的url放在已创建的服务器中,另一个请求下载zip文件?

3 个答案:

答案 0 :(得分:11)

当然可以这样做!但只有新浏览器支持此功能。

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();

答案 1 :(得分:7)

本机答案是否定的!

但你可以这样做。

您的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));

?>

答案 2 :(得分:2)

您无法使用ajax下载文件。

如果你只想要一个请求,那么抛弃ajax并将一个隐藏的iframe附加到页面上,以php文件为源。

这会限制您获取请求。

例如:

$('#id').click(function(){

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

});
相关问题