1、设置 a
标签的download
属性,可以设置文件名:
<a href='http://192.168.1.1/abcd.xlsx' download='模板.xlsx'>下载</a>
这种写法有个前提:
href
的下载地址和当前网站地址必须是同源的,否则download
不生效。
2、如果不同源,怎么办?
// 封装一个 download 方法
<el-button @click="download"></el-button>
function download() {
const x = new window.XMLHttpRequest();
x.open('GET', 'http://192.168.1.1/abcd.xlsx', true);
x.responseType = 'blob';
x.onload = () => {
const url = window.URL.createObjectURL(x.response);
const a = document.createElement('a');
a.href = url;
a.download = 'file.xlsx';
a.click();
};
x.send();
}