a标签下载文件设置download无效

SangFall / 2024-03-19 / 原文

场景:通过接口获取文件信息,再动态生成a标签,添加href、download,点击文件下载后,文件名并不是设置的download
问题:接口返回数据的文件url域名跟当前系统域名不一致,导致download失效
解决方案:采用原生请求设置responseType来实现指定download下载
<div @click="download">点击下载</div>
...
download () {
  axios.post().then(res => {
    const a = document.createElement('a');
    a.href = res.fileUrl;
    a.target = '_blank';
    a.download = res.fileName;

    const xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';

    xhr.onload = () => {
      a.href = URL.createObjectURL(xhr.response);
      document.body.appendChild(a);
      a.click();
      a.remove();
    }

    xhr.open('GET', a.pathname);
    xhr.send();
  })
}