function download (data, url) {
let xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.responseType = 'blob';
xhr.setRequestHeader('Content-Type','application/json;charset=utf-8');
xhr.onload = function (){
if(this.status==200){
let blob = this.response;
if(blob && blob.size > 0){
let fileName = getFileNameFromResponse(xhr.getResponseHeader("content-disposition"));
// 创建一个临时链接并模拟点击进行下载
let a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = fileName;
a.click();
} else {
console.error("下载失败");
}
}
}
xhr.send(JSON.stringify(data));
}
// 根据响应头获取文件名
function getFileNameFromResponse(contentDisposition) {
var matchResult = /fileName[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
if (matchResult != null && matchResult[1]) {
return decodeURIComponent(matchResult[1].replace(/['"]/g, ""));
}
return "download";
}
前端js post请求下载文件
于 2023-12-26 17:34:16 首次发布