【发布时间】:2018-01-19 06:20:09
【问题描述】:
我有一个 API-Server 可以响应这样的请求:
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 强制下载对话框。我在这里阅读了多个线程。但相同的线程不会告诉我 我怎样才能获得直接下载网址。还是不幸我把事情搞混了?
这是我所拥有的:
客户端 (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;
}
解决方案:
Rob 为我指明了正确的方向。我实际上不需要发出GET Ajax 请求。所以最终的 jQuery 函数看起来就像这样并且可以工作:
$(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 我正在尝试在我的客户端上获取用 HTML / jQuery 编写的“另存为”对话框。
-
好的,但是您提到的建议解决方案有什么问题?你说你知道你不能用 ajax 来做。
-
问题是它在客户端上不起作用,这意味着不会出现“另存为”对话框。我可能把事情搞混了,因为它不能通过 Rob 提供的解决方案起作用。无论如何谢谢lexith!
标签: javascript php jquery ajax