js下载文件重命名不生效(a.download修改fileName不生效)解决方法-(跨域问题)

众所周知,a标签中download属性可以更改下载文件的文件名。

但是只适用于同源文件,如果是跨域的话,download属性就会失效。


第一种方式:使用XMLHttpRequest

handleDownload(item) {
    var xml = new XMLHttpRequest();
    xml.open('GET', item.fileUrl, true);
    xml.responseType = 'blob';
    xml.onload = function () {
        var url = window.URL.createObjectURL(xml.response);
        var a = document.createElement('a');
        a.href = url;
        a.download = item.fileName;
        a.click();
    };
    xml.send();
},

第二种方式:使用axios

import axios from 'axios'
downloadFile(item) {
  axios
  .get(item.fileUrl, { responseType: 'blob' })
  .then(res => {
    const blob = new Blob([res.data])
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download =item.fileName
    link.click()
    URL.revokeObjectURL(link.href)
  })
  .catch(console.error)
},

猜你喜欢

转载自blog.csdn.net/snows_l/article/details/127979005