问题描述
更新 20140702:
Update 20140702:
- The solution
- Detailed answer as a blog post
(但我' m标记其他答案之一被接受而不是我自己的
,因为它让我在中途,并奖励努力)
(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)
似乎通过< a href =...>
的链接设置HTTP请求标头是不可能的,只能使用 XMLHttpRequest
。
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)
}
});
});
jsfiddle
jsfiddle http://jsfiddle.net/guest271314/SJYy3/
这篇关于如何设置HTTP GET请求的头文件,并触发文件下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!