donwload-tools.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import SimpleProgress from '@/components/SimpleProgress'
  2. import handleClipboard from '@/utils/clipboard'
  3. import { isWeChat } from '@/utils/validator'
  4. import Vue from 'vue'
  5. import { Dialog } from 'vant'
  6. let uuid = 0 // 进度条id
  7. export async function downloadWithUrl(downUrl, fileName, self) {
  8. const h = self.$createElement
  9. let progressRef, tiemer
  10. const notification = self.$notify({
  11. title: '提示',
  12. message: h('div', {}, [
  13. h('div', {}, `正在下载${fileName},请勿重复操作!`),
  14. h(SimpleProgress, { ref: `progress${uuid}` }),
  15. ]),
  16. duration: 0,
  17. })
  18. self.$nextTick(() => {
  19. progressRef = self.$refs[`progress${uuid}`]
  20. tiemer = setInterval(() => {
  21. if (progressRef.percentage < 90) {
  22. progressRef.percentage += 2
  23. } else {
  24. clearInterval(tiemer)
  25. }
  26. }, 500)
  27. })
  28. try {
  29. const data = await fetch(downUrl, {
  30. headers: { 'X-Token': self.$store.getters.accessToken },
  31. })
  32. if (data.redirected) {
  33. const resultData = await data.json()
  34. console.log(resultData.code)
  35. // 登录过期
  36. if (resultData.code === -99) {
  37. notification && notification.close()
  38. const result = await Dialog.alert({
  39. title: '提示',
  40. message: '登录已过期,请重新登录',
  41. theme: 'round-button',
  42. confirmButtonColor: 'linear-gradient(to left, #404040, #101010)',
  43. })
  44. Vue.prototype.$removeStorage(
  45. self.$store.getters.routePrefix,
  46. 'userInfo'
  47. )
  48. self.$store.dispatch('user/logout')
  49. if (result === 'confirm') {
  50. // redirect(self.$store.getters.routePrefix)
  51. self.$router.replace(self.$store.getters.routePrefix)
  52. }
  53. return
  54. }
  55. }
  56. const res = await data.blob()
  57. const link = document.createElement('a')
  58. const url = URL.createObjectURL(res)
  59. link.href = url
  60. link.download = fileName
  61. link.click()
  62. console.log(url)
  63. URL.revokeObjectURL(url)
  64. } catch (err) {
  65. self.$message.error(`下载${fileName}失败`)
  66. console.log(err)
  67. } finally {
  68. clearInterval(tiemer)
  69. progressRef.percentage = 100
  70. notification && notification.close()
  71. }
  72. }
  73. // 通过链接下载
  74. export default function downloadFile(downUrl, fileName, self, $event) {
  75. if (isWeChat()) {
  76. return handleClipboard(
  77. downUrl,
  78. $event,
  79. '下载链接已复制到剪切板,请粘贴到浏览器中下载'
  80. )
  81. } else {
  82. downloadWithUrl(downUrl, fileName, self)
  83. }
  84. }