在开发中涉及到下载需求,日常进行记录
1. API解耦之后,在接口请求接口里写入 responseType: "blob"
/**
* 选择性导出为excel
* @param {end,start} params 开始时间和结束时间
* @returns
*/
export function volunExcel(params) {
return request({
url: "/check/excel",
method: "GET",
params,
responseType: "blob",
});
}
2. 在该请求的回调里,原生创建a标签,并设置其URL及属性(download属性,设置下载后的文件名)
volunExcel({
start: startTime,
end: endTime,
}).then((res) => {
const link = document.createElement("a");
link.target = "_blank";
link.style.display = "none";
link.href = window.URL.createObjectURL(new Blob([res]));
//方式一:强制设置下载后的文件名为志愿者报名统计.xlsx
link.setAttribute("download", "志愿者报名统计.xlsx"