后台可以通过提供下载链接的方式让前端完成下载功能,这个多简单多粗暴多招人喜欢,只要location.href=`${url}`或者window.open(`${url}`)就结束了。
但是后台也会通过另一种方式提供下载,即前端请求接口返回二进制数据的方式。这种方式个人认为好处就是可以在网络延时比较大的时候,方便加个loading吧,谁知道呢。
那么,第二种方式前端要如何搞定呢,主要是使用Blob的方式,这个地方没啥太复杂的,直接上代码了
const download = (res, name) => {
const blob = new Blob([res])
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, name);
} else {
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.setAttribute("download", name);
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}
};
来源:oschina
链接:https://my.oschina.net/wangch5453/blog/3159926