在开发中涉及到下载需求,日常进行记录
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");
//方式二:组合文件名
let fileName = item.attachmentName;
let fileUrl = item.attachmentUrl;
const extName = fileUrl.substring(
fileUrl.lastIndexOf('.')
);
fileName = fileName + extName;
link.download = fileName;
//方式三:可随机生成文件名,可通过uuid或者其他方式生成,暂不做介绍
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
});
本文介绍了在JavaScript中处理下载需求的方法,通过设置接口请求的responseType为'blob',并在回调中利用原生a标签结合download属性实现文件下载。
1599

被折叠的 条评论
为什么被折叠?



