XMLHttpRequest实现下载文件的功能

var xhr = new XMLHttpRequest();
xhr.open(‘get’, ‘请求url’);
//设置请求头
xhr.setRequestHeader(window.AUTH_HEADER, window.localStorage.getItem(window.TOKEN_NAME));
//设置响应类型
xhr.responseType = ‘blob’;
xhr.onload = function (e) {
if (this.status == 200) {
var filename = xhr.getResponseHeader(“Content-disposition”).slice(9); //根据后台返回进行修改
var blob = this.response;
var a = document.createElement(‘a’);
var url = URL.createObjectURL(blob);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
}
};
xhr.send()

你可能感兴趣的:(javascript,servlet,前端)