下载接口

image.png
接口是一个post请求,返回的是一个文件流。

配置 axios

响应拦截

  1. httpRequest.interceptors.response.use(function(response) {
  2. const headers = response.headers
  3. // 文件下载
  4. if (headers['content-type'] === 'application/vnd.ms-excel' || headers['content-disposition']) {
  5. return response
  6. }
  7. });

配置接口:

添加:responseType: ‘blob’

  1. export function classAttendanceDetailExport(data) {
  2. return httpRequest({
  3. method: 'post',
  4. url: "/mgr/report/classAttendanceDetail/export",
  5. data: data,
  6. responseType: 'blob'
  7. });
  8. }

下载功能:

  1. /**
  2. * 导出表格
  3. */
  4. async exportTable() {
  5. try {
  6. const res = await httpRequest.classAttendanceDetailExport({
  7. classId: this.row.classId,
  8. groupId: this.row.groupId,
  9. });
  10. const filename = `课程到课统计${forMatDate(new Date(),'yyyyMMddhhmmss')}`;
  11. handleFileStreamDownload(res,filename,'.xls');
  12. } catch (error) {
  13. console.log("导出表格-出错了", error)
  14. }
  15. },
  16. /**
  17. * 下载文件
  18. * @param {*} res
  19. * @param {*} filename 文件名
  20. * @param {*} format 文件格式
  21. * @returns
  22. */
  23. export function handleFileStreamDownload(res,filename,format){
  24. if (!res) {
  25. return
  26. }
  27. if (window.navigator.msSaveBlob) { // IE以及IE内核的浏览器
  28. try {
  29. window.navigator.msSaveBlob(res.data, `${filename}${format}`)
  30. } catch (e) {
  31. console.log(e)
  32. }
  33. } else {
  34. let url = window.URL.createObjectURL(new Blob([res.data]))
  35. let link = document.createElement('a')
  36. link.style.display = 'none'
  37. link.href = url
  38. link.setAttribute('download', `${filename}${format}`)// 文件名
  39. document.body.appendChild(link)
  40. link.click()
  41. document.body.removeChild(link) // 下载完成移除元素
  42. window.URL.revokeObjectURL(url) // 释放掉blob对象
  43. }
  44. }