使用Javascript添加自定义http头文件并触发文件下载 [英] Using Javascript to add custom http header and trigger file download
问题描述
我想通过浏览器启动一个简单的文件下载,但必须使用自定义HTTP标头传递访问令牌:
I would like to start a simple file download through the browser, however an access token must be passed with a custom HTTP header:
GET https://my.site.com/some/file
Authorization: access_token
如何在站点URL之后注入授权:标头?
我知道可以使用查询字符串来做到这一点,但是我想使用头文件来执行。
How can I inject the Authorization: header following the site URL? I know it's possible to do that using query string, but I want to do it using headers.
我熟悉XMLHttpRequest,但是我明白它不会触发下载,它只读取内容,至少要下载的文件是几百MB。
I'm familiar with XMLHttpRequest, but as far as I understand it does not trigger download, it only reads content and the file I want to download is few hundred MBs at least.
xhr.setRequestHeader('Authorization', 'access_token');
这看起来像一个简单的任务,但我没有经验的编码器,所以任何帮助都会很好。谢谢。
This looks like a simple task, but I'm inexperienced coder so any help would be nice. Thanks.
推荐答案
我认为这解决了您的问题:
I think this solves your problem:
function toBinaryString(data) {
var ret = [];
var len = data.length;
var byte;
for (var i = 0; i < len; i++) {
byte=( data.charCodeAt(i) & 0xFF )>>> 0;
ret.push( String.fromCharCode(byte) );
}
return ret.join('');
}
var xhr = new XMLHttpRequest;
xhr.open( "GET", "https://my.site.com/some/file" );
xhr.addEventListener( "load", function(){
var data = toBinaryString(this.responseText);
data = "data:application/text;base64,"+btoa(data);
document.location = data;
}, false);
xhr.setRequestHeader("Authorization", "access_token" );
xhr.overrideMimeType( "application/octet-stream; charset=x-user-defined;" );
xhr.send(null);
修改后的答案 https://stackoverflow.com/a/10518190/2767026 以满足您的需求。
Modified answer https://stackoverflow.com/a/10518190/2767026 to fit your needs.
这篇关于使用Javascript添加自定义http头文件并触发文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!