前端文件下载

168 阅读2分钟

文件下载

在前端下载文件是个很通用的需求,一般后端会提供下载的方式有两种: 1.直接返回文件的网络地址(一般用在静态文件上,比如图片以及各种音视频资源等) 2.返回文件流(一般用在动态文件上,比如根据前端选择,导出不同的统计结果 excel 等)

方式一:《a》标签 download

1.简单写法

<a href="https://www.baidu.top.pdf" download="附件.pdf">下载文件</a>

缺点:download 只在同源 URL 或 blob: 、 data: 协议起作用(除非后端配置 Content-Disposition 为 attachment) 2.编程式写法

function Download() { window.location.href = 'www.baidu.pdf' }

跨域时Blob转换 在非同源请情况下可以将资源当成二进制的 blob 先拿到手,再进行 《a》 的下载处理。 URL.createObjectURL 可以给 File 或 Blob 生成一个URL

function Download() { 
axios({ url: "www.baidu.pdf", method: 'GET', responseType: 'blob', // 这就是转化为blob文件流 
headers: { token: 'sss' // 可以携带token } }).then(res => { 
// 生成访问 blob 的 URL
const href = URL.createObjectURL(res.data) 
a标签下载
const box = document.createElement('a') 
box.download = '附件.pdf' 
box.href = href
box.click() 
// 删除映射,释放内存 
URL.revokeObjectURL(url);
}) }

使用blob注意事项

接口设置 responseType: 'blob'

拦截器解构设置 if(res.data instanceof blob)return res.data

如果配合excel下载

用file-server这个包把二进制流转成excel数据
import { saveAs } from 'file-saver'
saveAs(res.data, '员工导入模版.xlsx')

方式二:axios下载

发送axios请求,当我们的请求成功后,我们会拿到响应体Response,这个Response就是我们要下载的内容。 然后我们把它转换成Blob对象,通过URL.createObjectURL来创建一个URL,最后使用a标签的download属性来实现文件下载。

const blob = new Blob([xhr.response], { type: 'text/html' }) const a = document.createElement('a') a.href = URL.createObjectURL(blob) a.download = 'baidu.html' a.click()

方式三 后台做

export const getExportTemplate = () => {
  return resquest({
    url: '/sys/user/import/template',
    responseType: 'blob' // 二进制文件流
  })
}

async getTemplate() {
      const data = await getExportTemplate()
      saveAs(data, '员工导入模版.xlsx')
    },

参考资料juejin.cn/post/696684…