我有一個API的服務器誰響應這樣的請求:困難下載文件時使用jQuery(GET)
http://localhost:8080/slim3/public/api/v1/files/Test1.jpg
http://localhost:8080/slim3/public/api/v1/files/Test2.txt
...
如果我把這樣的URL到我的瀏覽器,我可以得到的下載提示。現在我正在努力通過jQuery/Ajax來處理文件的下載。 我在Stackoverflow上找到的每個線程都告訴我發回實際的下載url,並通過window.location
打開它。我不明白這怎麼可能 當我的服務器已經爲我下載的文件,我只需要「抓住」它在客戶端?
很明顯,我無法通過jQuery/Javascript強制下載對話框。我在這裏閱讀了多個主題。但同樣的線程不會告訴我 我如何獲得直接下載url。或者不幸的是我在這裏混合了一些東西?
以下是我有:
客戶端(jQuery的)
$(document).ready(function(){
$(document).on('click', '#file', function(e){
e.preventDefault();
var filename = $(this).data('url');
$.ajax({
type : "GET",
cache: false,
url : "http://localhost:8080/slim3/public/api/v1/files/" + filename,
success : function(data) {
console.log(data) // the console writes nothing
//window.location = "data:application/octet-stream," + encodeURIComponent(data); // not working
//var downloadUrl = data.url; // not working
//window.location = downloadUrl; // // not working
},
error : function(data) {}
});
});
});
服務器(PHP)
public function show($request, $response, $args)
{
$file = 'C:\xampp\htdocs\slim3\storage\Test1.jpg';
$res = $response->withHeader('Content-Description', 'File Transfer')
->withHeader('Content-Type', 'application/octet-stream')
->withHeader('Content-Disposition', 'attachment;filename="'.basename($file).'"')
->withHeader('Expires', '0')
->withHeader('Cache-Control', 'must-revalidate')
->withHeader('Pragma', 'public')
->withHeader('Content-Length', filesize($file));
readfile($file);
return $res;
}
解決方案:
羅布指出我在正確的方向。我其實不需要做GET Ajax
請求。因此,最終的jQuery函數如下exacty像這樣和工作原理:
$(document).on('click', '#file', function(e){
e.preventDefault();
var filename = $(this).data('url');
window.location = "http://localhost:80/slimmi/public/api/v1/files/" + filename;
});
你能解釋一下你真正想做什麼嗎?我真的不明白你在問什麼。 – lexith
@lexith我試圖在我的客戶端上使用HTML/jQuery編寫的「另存爲」對話框。 – Magiranu
好的,但你提到的建議解決方案有什麼問題?你說你知道你不能用ajax做。 – lexith