<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<button id="b">donwload</button>
</body>
</html>
// 处理Blob数据下载
function executeDownload(data, fileName) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]));
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
alert("download success")
}
let url = "http://example"
let params = {}
// 发送请求,接收文件数据并解析文件名
$("#b").click(function(){
axios.post(
url,
params,
{responseType: 'blob'}
)
.then(res => {
let reader = new FileReader();
let data = res.data;
reader.onload = e => {
if (e.target.result.indexOf('Result') != -1 && JSON.parse(e.target.result).Result == false) {
// 进行错误处理
} else {
// 获取响应,前后端分离需要后端主动暴露响应头
// resp.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
let contentDisposition = res.headers['content-disposition'];
if (contentDisposition) {
fileName = window.decodeURI(res.headers['content-disposition'].split('=')[1], "UTF-8");
}
executeDownload(data, fileName);
}
};
reader.readAsText(data);
})
})