a标签设置下载设置文件名

设置 a 标签的 download属性,可以重置 文件名。如下代码,文件名重置为 file.xlsx。

<a href='http://192.168.1.1/abcd.xlsx' download='file.xlsx'>下载</a>

封装一个download方法

const downlad = (url: any, fileName: any) => {
        const newUrl = url
        const link = document.createElement('a')
        link.href = newUrl
        link.download = fileName 
        link.target = '_blank'
        link.style.display = 'none'
        document.body.append(link)
        link.click()
    }

 

这种写法有个前提:href 的下载地址 和 当前网站地址 必须是 同源的,否则download不生效。 

如果不同源,还有一种方法,代码如下:

// 封装一个download方法

const downlad = (urls: any, fileName: any) => {
        const x = new window.XMLHttpRequest();
        x.open('GET', urls, true);
        x.responseType = 'blob';
        x.onload = () => {
            const url = window.URL.createObjectURL(x.response);
            const a = document.createElement('a');
            a.href = url;
            a.target = '_blank'
            a.download = fileName;
            a.style.display = 'none'
            document.body.append(a)
            a.click();
        };
        x.send();
    }

 

来源:https://blog.csdn.net/sinat_36728518/article/details/123525637

posted @ 2022-08-26 17:06  webnote  阅读(6908)  评论(0编辑  收藏  举报