useDownload.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import { ElNotification, ElMessage, ElLoading } from 'element-plus'
  2. import { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
  3. import { blobValidate } from '@/utils/common'
  4. import axios from 'axios'
  5. import { globalHeaders } from '@/api'
  6. let downloadLoadingInstance: LoadingInstance
  7. import { saveAs } from 'file-saver'
  8. import errorCode from '@/utils/errorCode'
  9. /**
  10. * @description 接收数据流生成 blob,创建链接,下载文件
  11. * @param {Function} api 导出表格的api方法 (必传)
  12. * @param {String} tempName 导出的文件名 (必传)
  13. * @param {Object} params 导出的参数 (默认{})
  14. * @param {Boolean} isNotify 是否有导出消息提示 (默认为 true)
  15. * @param {String} fileType 导出的文件格式 (默认为.xlsx)
  16. * */
  17. export const useDownload = async (
  18. api: (param: any) => Promise<any>,
  19. tempName: string,
  20. params: any = {},
  21. isNotify: boolean = true,
  22. fileType: string = '.xlsx',
  23. fileName?: string
  24. ) => {
  25. if (isNotify) {
  26. ElNotification({
  27. title: '温馨提示',
  28. message: '如果数据庞大会导致下载缓慢哦,请您耐心等待!',
  29. type: 'info',
  30. duration: 3000
  31. })
  32. }
  33. const saveAsFn = (text: string | Blob, name: string | undefined, opts?: any) => {
  34. saveAs(text, name, opts)
  35. }
  36. const printErrMsg = async data => {
  37. const resText = await data.text()
  38. const rspObj = JSON.parse(resText)
  39. const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
  40. ElMessage.error(errMsg)
  41. }
  42. try {
  43. const data = await api(params)
  44. const isBlob = await blobValidate(data)
  45. if (isBlob) {
  46. const blob = fileType == 'zip' ? new Blob([data], { type: 'application/zip' }) : new Blob([data])
  47. const name = fileType == 'zip' ? fileName : `${tempName}_${new Date().getTime()}${fileType}`
  48. saveAsFn(blob, name, null)
  49. console.log('%s ====>>>导出成功', tempName)
  50. } else {
  51. printErrMsg(data)
  52. }
  53. } catch (error) {
  54. console.log(error)
  55. ElMessage.error('下载文件出现错误,请联系管理员!')
  56. }
  57. }
  58. const baseURL = import.meta.env.VITE_API_URL
  59. export default {
  60. async oss(ossId: string | number) {
  61. const url = baseURL + '/resource/oss/download/' + ossId
  62. downloadLoadingInstance = ElLoading.service({ text: '正在下载数据,请稍候', background: 'rgba(0, 0, 0, 0.7)' })
  63. try {
  64. const res = await axios({
  65. method: 'get',
  66. url: url,
  67. responseType: 'blob',
  68. headers: globalHeaders()
  69. })
  70. const isBlob = blobValidate(res.data)
  71. if (isBlob) {
  72. const blob = new Blob([res.data], { type: 'application/octet-stream' })
  73. saveAs(blob, decodeURIComponent(res.headers['download-filename'] as string))
  74. } else {
  75. this.printErrMsg(res.data)
  76. }
  77. downloadLoadingInstance.close()
  78. } catch (r) {
  79. console.error(r)
  80. ElMessage.error('下载文件出现错误,请联系管理员!')
  81. downloadLoadingInstance.close()
  82. }
  83. },
  84. async printErrMsg(data: any) {
  85. const resText = await data.text()
  86. const rspObj = JSON.parse(resText)
  87. const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
  88. ElMessage.error(errMsg)
  89. },
  90. async zip(url: string, name: string) {
  91. url = baseURL + url
  92. downloadLoadingInstance = ElLoading.service({ text: '正在下载数据,请稍候', background: 'rgba(0, 0, 0, 0.7)' })
  93. try {
  94. const res = await axios({
  95. method: 'get',
  96. url: url,
  97. responseType: 'blob',
  98. headers: globalHeaders()
  99. })
  100. const isBlob = blobValidate(res.data)
  101. if (isBlob) {
  102. const blob = new Blob([res.data], { type: 'application/zip' })
  103. saveAs(blob, name)
  104. } else {
  105. this.printErrMsg(res.data)
  106. }
  107. downloadLoadingInstance.close()
  108. } catch (r) {
  109. console.error(r)
  110. ElMessage.error('下载文件出现错误,请联系管理员!')
  111. downloadLoadingInstance.close()
  112. }
  113. }
  114. }