a标签设置下载文件名无效的解决方案

1,350 阅读1分钟

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();
}

原文:www.cnblogs.com/sws-kevin/p…