2014-05-15 29 views
0

我想知道是否有可能做一個ajax post請求到一個特定的網址,並在數據中只接收一個zip文件請求?或者我必須發送兩個請求...一個,爲了讓zip文件的URL在已經創建的服務器中,另一個可以下載zip文件?從ajax下載zip文件jquery post請求

回答

5

天然答案是否定的!

但你可以這樣做。

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

?> 
0

你不能用ajax下載文件。

如果你只想要一個請求,然後拋棄ajax並將一個隱藏的iframe添加到頁面,以php文件作爲源。

雖然這會限制您獲取請求。

如:

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

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

}); 
9

當然,你可以做到這一點!但只有新的瀏覽器支持這一點。

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

由於文件大小達到幾兆字節,瀏覽器是否有可能崩潰?用戶是否會看到下載進度?我想他不會 - 如果我得到的解決方案是正確的... – SimonSimCity

+1

@SimonSimCity檢查出[FileSaver](https://github.com/eligrey/FileSaver.js/)庫,這應該給你一些關於尺寸的想法限制。您可以通過xhr進度事件跟蹤下載進度,請參閱[MDN doc](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) – Mikk