Generally, when doing data statistics, the back-end will not save the downloaded things on the server and return the download address, but directly return the file stream. At this time, the front-end will receive the processing stream by itself.
Processing flow
Let me talk about the process of receiving and processing
- Store the stream we received in the object URL
- Create an a tag and bind the object URL to the a tag, and then mount the a tag to the dom tree
- Trigger the click event of the a tag through js to download the file
- Release the url and a tag we created
Specific code implementation
Take vue as an example, using axios request
this.$axios.post("/downloadDt", param).then(res => {
// 创建一个 a 标签,并隐藏 a 标签
let a = document.createElement("a");
a.style.display = "none";
// 对象 URL 绑定到 a 标签上
a.href = window.URL.createObjectURL(new Blob([res.data]));
// 给 a 标签添加 download 属性 与 文件名
a.setAttribute("download", `数据报表${
new Date().toLocaleString()}.xls`);
// 把 a 标签挂载到 dom 树上并执行 a 标签的 click 事件
document.body.appendChild(a);
a.click();
// 释放我们创建的 url 和 a 标签
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}