前端实现文件下载

95 阅读1分钟

场景:

后端API返回文件内容,这时候能不经过服务端而在前端直接生成下载任务,能节省不少的资源和时间开销

前端代码大致如下:

const url = window.URL.createObjectURL(new Blob([filecontent]))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', name)
link.click()
window.URL.revokeObjectURL(url)