接口请求下载文件

it2026-10-05  2

使用< a>标签 <a href="../../static/xxx.xlsx" download="xxx.xlsx">下载</a>

直接点击可以下载,需要注意的是download属性,当不加download属性时,如果文件格式为txt、pdf、jpg等浏览器支持直接打开的文件格式,那么不会下载,而是浏览器直接打开;添加download属性之后,就会下载,并且下载文件默认命名为你download属性的值

使用window.open() window.open("../../static/xxx.xlsx") window.open("https://cee/edit/xxx.xlsx") 返回值得处理,其实也是< a>标签

首先是请求接口会返回res,然后再调用下面的方法即可

ExportCSV(res) { console.log(res) const blob = new Blob([res.data], { type: "application/vnd.ms-excel" }) const filename = decodeURI((res.headers['content-disposition'] && res.headers['content-disposition'].split(';')[1].split('=')[1])) || 'file.xls' // 创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件 if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, filename); } else { const elink = document.createElement('a') elink.download = filename elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() URL.revokeObjectURL(elink.href) // 释放URL 对象 document.body.removeChild(elink) } }
最新回复(0)