前端实现文件下载(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 @   安静的女汉纸  阅读(2280)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示