donwload-tools.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import SimpleProgress from '@/components/SimpleProgress'
  2. import handleClipboard from '@/utils/clipboard'
  3. import { isWeChat } from '@/utils/validator'
  4. let uuid = 0 // 进度条id
  5. export async function downloadWithUrl(downUrl, fileName, self) {
  6. const h = self.$createElement
  7. let progressRef, tiemer
  8. const notification = self.$notify({
  9. title: '提示',
  10. message: h('div', {}, [
  11. h('div', {}, `正在下载${fileName},请勿重复操作!`),
  12. h(SimpleProgress, { ref: `progress${uuid}` }),
  13. ]),
  14. duration: 0,
  15. })
  16. self.$nextTick(() => {
  17. progressRef = self.$refs[`progress${uuid}`]
  18. tiemer = setInterval(() => {
  19. if (progressRef.percentage < 90) {
  20. progressRef.percentage += 2
  21. } else {
  22. clearInterval(tiemer)
  23. }
  24. }, 500)
  25. })
  26. try {
  27. const data = await fetch(downUrl)
  28. const res = await data.blob()
  29. const link = document.createElement('a')
  30. const url = URL.createObjectURL(res)
  31. link.href = url
  32. link.download = fileName
  33. link.click()
  34. console.log(url)
  35. URL.revokeObjectURL(url)
  36. } catch (err) {
  37. self.$message.error(`下载${fileName}失败`)
  38. } finally {
  39. clearInterval(tiemer)
  40. progressRef.percentage = 100
  41. notification && notification.close()
  42. }
  43. }
  44. // 通过链接下载
  45. export default function downloadFile(downUrl, fileName, self, $event) {
  46. if (isWeChat()) {
  47. return handleClipboard(
  48. downUrl,
  49. $event,
  50. '下载链接已复制到剪切板,请粘贴到浏览器中下载'
  51. )
  52. } else {
  53. downloadWithUrl(downUrl, fileName, self)
  54. }
  55. }