前端实现文件下载(a标签文件下载)

一、链接地址下载

const link = document.createElement('a');
const url = `url下载链接地址`
link.href = url;
link.setAttribute('download', '文件名'); //window下载窗口名称自定义
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

 

二、后台接口返回文件信息

await api.downloadFile(item).then(res => { //接口请求
    const link = document.createElement('a');
    //window.URL.createObjectURL() 方法用于创建一个表示指定对象的 URL,需要传入一个 Blob 对象或者 File 对象作为参数
    link.href = window.URL.createObjectURL(new Blob([res]));//将内容转为blob格式
    link.setAttribute('download', '文件名');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
})

 

三、跨域问题,setAttribute设置文件名不生效

如果在setAttribute时发现a标签中download属性发生改变,但是window文件窗口的名称未改变,那么可能是因为服务端返回的响应头中设置了文件名。这时候,浏览器会优先使用服务端返回的文件名作为下载文件的名称,而忽略前端设置的下载属性

//解决方案
//在服务端返回的响应头中设置一个特殊的 Content-Disposition 字段,强制浏览器使用前端设置的下载属性
Content-Disposition: attachment; filename='文件名'  

 

摘自:https://blog.csdn.net/jyl919221lc/article/details/135126552

 

posted @ 2024-05-06 10:13  安静的女汉纸  阅读(765)  评论(0编辑  收藏  举报