Wiidede's blog Wiidede's blog
  • 前端
  • Python
  • 算法
  • 生活
  • 其他
  • 分类
  • 标签
  • 归档
  • 关于我
  • 赞赏
  • 我的小站 (opens new window)
GitHub (opens new window)

Wiidede

小的的写前端
  • 前端
  • Python
  • 算法
  • 生活
  • 其他
  • 分类
  • 标签
  • 归档
  • 关于我
  • 赞赏
  • 我的小站 (opens new window)
GitHub (opens new window)
  • 整理一些css样式
  • vue隔代组件层层动态插槽并且附带数据
  • vue判断字符串是否溢出来显示弹窗、解决el-table tooltip 内过多导致无法显示,内容闪烁
  • 整理一些js写法
  • ElementUI timePicker 增加此刻按钮 引发的dom操作的学习
  • 毕业设计(水表识别)前端知识整理
  • html小知识
  • axios请求api然后下载文件
  • vue3+ts根据高度改变元素的透明度
  • vue3 + ElementPlus 换肤方案(Css变量)
  • Moment的一些使用方法
  • echarts基础vue组件
  • element UI el-date-picker 年月日切换组件
  • 可以不选择的el-radio单选框
  • vue的小技巧总结
  • 全局动态权限判断(Vue指令)
  • vue-anchor 探索
  • Deep Dive with Evan You 笔记
  • 前端基础知识查漏补缺
  • WebPack 知识总结
  • 我写的一些可以日后参考的代码
  • 接口变化后,封装接口函数,改变返回内容
  • 项目组件整理
  • 前端框架设计想发
  • 全局进度条
  • 带有token的图片vue组件:authImg,使用axios下载图片
  • 前端npm包推荐
  • 给ElInputNumber添加prefix
  • ElPagination添加页数总数
  • el-tab做成chrome类似的tab样式
  • vue-grid-layout-组件配置
  • 项目数据字典封装
  • 图表组件响应式探索
  • ElementPlus表格table列自动合并composition
  • 简单的curd组件封装
  • ElementPlus表格自定义合计列composition
  • 一些处理表格数据composition api
  • div内容溢出后,内容向左悬浮,vue组件封装
  • 文本数字溢出后,按比例缩小,vue组件封装
  • 表格使用async-validator检验composition
  • ElementPlus Form一些简单的组件整合
  • arco-design快速使用tailwind的颜色、unocss动态颜色
  • 前端
wiidede
2021-08-12

axios请求api然后下载文件

# axios请求api然后下载文件

首先我们需要把axios实例建立好,在这一步,你可以把接口需要的token等内容加入进去

const instance = axios.create({
    headers: {
        'jwt-token': Auth.getJwtToken()
    },
    responseType: 'blob'
});
1
2
3
4
5
6

然后我们发起请求,这时候我们可以让页面进入加载状态,然后不管怎么样,我们需要结束加载

startLoading();
const res = await instance.request({url, method, params, data}).finally(endLoading);
1
2

然后开始处理接口返回的内容

如果后端报错,这里会返回JSON格式的文件,需要我们自己取处理

这里的errorFunc是调用者传进来的,这样方便调用者更好的显示错误

最后我们只需要把取到的Blob下载下来,我们可以随便搜到一个downloadBlob函数

if (!filename) {
  const contentDisposition = res.headers['content-disposition'];
  filename = contentDisposition ? decodeURIComponent(contentDisposition.split('filename=')[1]) : '文件';
}
const contentType = (res.headers['content-type'] && res.headers['content-type'].split(';')[0]) ||
  'application/octet-stream';
if (res.data instanceof Blob) {
  if (res.data.type === 'application/json') { // 处理后端报错的情况
    const rawText = await res.data.text();
    const raw = JSON.parse(rawText);
    if (raw.code && raw.code !== 0) {
      console.warn(raw.message);
      errorFunc && typeof errorFunc === 'function' && errorFunc(raw.message);
    }
  } else {
    downloadBlob(res.data, filename);
  }
} else {
  const blob = new Blob([res.data], {
    type: contentType
  });
  downloadBlob(blob, filename);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

接下来是完整的代码

const getFile = async ({url, method = 'get', params = {}, data = {}, errorFunc, filename}) => {
  const instance = axios.create({
    headers: {
      'jwt-token': Auth.getJwtToken()
    },
    responseType: 'blob'
  });
  startLoading();
  const res = await instance.request({url, method, params, data}).finally(endLoading);
  if (!filename) {
    const contentDisposition = res.headers['content-disposition'];
    filename = contentDisposition ? decodeURIComponent(contentDisposition.split('filename=')[1]) : '文件';
  }
  const contentType = (res.headers['content-type'] && res.headers['content-type'].split(';')[0]) ||
    'application/octet-stream';
  if (res.data instanceof Blob) {
    if (res.data.type === 'application/json') { // 处理后端报错的情况
      const rawText = await res.data.text();
      const raw = JSON.parse(rawText);
      if (raw.code && raw.code !== 0) {
        console.warn(raw.message);
        errorFunc && typeof errorFunc === 'function' && errorFunc(raw.message);
      }
    } else {
      downloadBlob(res.data, filename);
    }
  } else {
    const blob = new Blob([res.data], {
      type: contentType
    });
    downloadBlob(blob, filename);
  }
};

const downloadBlob = (blob, filename) => {
 if (typeof window.navigator.msSaveBlob !== 'undefined') {
  // IE doesn't allow using a blob object directly as link href.
  // Workaround for "HTML7007: One or more blob URLs were
  // revoked by closing the blob for which they were created.
  // These URLs will no longer resolve as the data backing
  // the URL has been freed."
  window.navigator.msSaveBlob(blob, filename);
  return;
 }
 // Other browsers
 // Create a link pointing to the ObjectURL containing the blob
 const blobURL = window.URL.createObjectURL(blob);
 const tempLink = document.createElement('a');
 tempLink.style.display = 'none';
 tempLink.href = blobURL;
 tempLink.setAttribute('download', filename);
 // Safari thinks _blank anchor are pop ups. We only want to set _blank
 // target if the browser does not support the HTML5 download attribute.
 // This allows you to download files in desktop safari if pop up blocking
 // is enabled.
 if (typeof tempLink.download === 'undefined') {
  tempLink.setAttribute('target', '_blank');
 }
 document.body.appendChild(tempLink);
 tempLink.click();
 document.body.removeChild(tempLink);
 setTimeout(() => {
  // For Firefox it is necessary to delay revoking the ObjectURL
  window.URL.revokeObjectURL(blobURL);
 }, 100);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#前端#axios#下载
上次更新: 2023/06/01, 12:40:50

← html小知识 vue3+ts根据高度改变元素的透明度→

Theme by Vdoing | Copyright © 2021-2023 Wiidede | Website use MIT License | Article content & logo use CC-BY-SA-4.0 License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式