登录  | 立即注册

游客您好!登录后享受更多精彩

查看: 621|回复: 4

vue,js,fetch请求数据流下载文件

[复制链接]

5

主题

0

回帖

45

积分

新手上路

积分
45
发表于 2024-1-29 19:54:02 | 显示全部楼层 |阅读模式
vue,js,fetch请求数据流下载文件

假设现在有一后台API提供访问,那么要想前端进行下载head头需要设置如下类型
  1. Content-Type:application/octet-stream
复制代码

下面两个head头建议也添加一下,虽然不是必须的(注意filename后面如果有中文,需要进行urlencode,否则会报错)
  1. Access-Control-Expose-Headers:Content-Disposition
  2. Content-Disposition:attachment;filename=rename.xlsx
复制代码

前端部分:
  1. fetch('/api', function (response) {
  2.    response.blob().then((blob) => {
  3.    saveBlobAs(blob, 'result.xls')
  4.             })
  5.         }, function (result) {
  6.    console.info("获取数据失败" + result.message);
  7.         })

  8. // 保存bolb的方法
  9. function saveBlobAs (blob, filename) {
  10.    if (window.navigator.msSaveOrOpenBlob) {
  11.       navigator.msSaveBlob(blob, filename)
  12.    } else {
  13.       const anchor = document.createElement('a')
  14.       const body = document.querySelector('body')
  15.       anchor.href = window.URL.createObjectURL(blob)
  16.       anchor.download = filename

  17.       anchor.style.display = 'none'
  18.       body.appendChild(anchor)

  19.       anchor.click()
  20.       body.removeChild(anchor)

  21.       window.URL.revokeObjectURL(anchor.href)
  22.    }
  23.     }
复制代码
这样就完事了
回复

使用道具 举报

0

主题

98

回帖

146

积分

注册会员

积分
146
发表于 2024-10-10 02:40:14 | 显示全部楼层
感谢LZ分享
回复

使用道具 举报

0

主题

108

回帖

161

积分

注册会员

积分
161
发表于 2024-10-10 03:55:25 | 显示全部楼层
1111111111111111111
回复

使用道具 举报

0

主题

100

回帖

149

积分

注册会员

积分
149
发表于 2024-10-10 05:10:22 | 显示全部楼层
11111111111
回复

使用道具 举报

0

主题

100

回帖

149

积分

注册会员

积分
149
发表于 7 天前 | 显示全部楼层
66666666666666
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|九尾社区 ( 皖ICP备2021001835号 )

GMT+8, 2024-10-18 22:28 , Processed in 0.206922 second(s), 22 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表