前端实现文件下载(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='文件名'  

猜你喜欢

转载自blog.csdn.net/jyl919221lc/article/details/135126552