问题描述
更新 20140702:
Update 20140702:
- The solution
- Detailed answer as a blog post
(但我打其他的答案之一。因为它让我半路上,并奖励努力)
(but I'm marking one of the other answers as accepted instead of my own,as it got me halfway there, and to reward the effort)
看来,设置一个HTTP请求头是不可能通过链接与< A HREF =...>
,并且只能使用做 XMLHtt prequest
。
It appears that setting a HTTP request header is not possible through links with <a href="...">
, and can only be done using XMLHttpRequest
.
不过,联系到URL是要下载(浏览器不应该导航到它的URL)的文件,我不知道这是可以使用AJAX来完成。
However, the URL linked to is a file that should be downloaded (browser should not navigate to its URL), and I am not sure is this can be done using AJAX.
此外,正在返回的文件是二进制文件,和AJAX不用于该
Additionally, the file being returned is a binary file, and AJAX is not intended for that.
如何将一去触发文件下载使用具有添加到它的自定义标题中的HTTP请求?
How would one go about triggering a file download with a HTTP request that has a custom header added to it?
推荐答案
尝试
HTML
<!-- placeholder ,
`click` download , `.remove()` options ,
at js callback , following js
-->
<a>download</a>
JS
$(document).ready(function () {
$.ajax({
// `url`
url: '/echo/json/',
type: "POST",
dataType: 'json',
// `file`, data-uri, base64
data: {
json: JSON.stringify({
"file": "data:text/plain;base64,YWJj"
})
},
// `custom header`
headers: {
"x-custom-header": 123
},
beforeSend: function (jqxhr) {
console.log(this.headers);
alert("custom headers" + JSON.stringify(this.headers));
},
success: function (data) {
// `file download`
$("a")
.attr({
"href": data.file,
"download": "file.txt"
})
.html($("a").attr("download"))
.get(0).click();
console.log(JSON.parse(JSON.stringify(data)));
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
});
});
http://jsfiddle.net/guest271314/SJYy3/
这篇关于如何设置一个HTTP GET请求头,并触发文件下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!