a标签跨域下载文件,解决download失效问题

a标签中download属性可以更改下载文件的文件名。但是如果是跨域的话,download属性就会失效。
解决方案:

<a @click="downloadFile(fileUrl,fileName)">下载文件</a>

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

参考:https://blog.csdn.net/qq_41914451/article/details/104559527

下篇介绍XMLHttpRequest()对象

你可能感兴趣的:(html)