123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- import SimpleProgress from '@/components/SimpleProgress'
- import handleClipboard from '@/utils/clipboard'
- import { isWeChat } from '@/utils/validator'
- import Vue from 'vue'
- import { Dialog } from 'vant'
- import { encrypt } from './crypto'
- let uuid = 0 // 进度条id
- export async function downloadWithUrl(downUrl, fileName, self) {
- const h = self.$createElement
- let progressRef, tiemer
- const notification = self.$notify({
- title: '提示',
- message: h('div', {}, [
- h('div', {}, `正在下载${fileName},请勿重复操作!`),
- h(SimpleProgress, { ref: `progress${uuid}` }),
- ]),
- duration: 0,
- })
- self.$nextTick(() => {
- progressRef = self.$refs[`progress${uuid}`]
- tiemer = setInterval(() => {
- if (progressRef.percentage < 90) {
- progressRef.percentage += 2
- } else {
- clearInterval(tiemer)
- }
- }, 500)
- })
- try {
- const data = await fetch(downUrl, {
- headers: { 'X-Token': self.$store.getters.accessToken },
- })
- if (data.redirected) {
- const resultData = await data.json()
- console.log(resultData.code)
- // 登录过期
- if (resultData.code === -99) {
- notification && notification.close()
- const result = await Dialog.alert({
- title: '提示',
- message: '登录已过期,请重新登录',
- theme: 'round-button',
- confirmButtonColor: 'linear-gradient(to left, #404040, #101010)',
- })
- Vue.prototype.$removeStorage(
- self.$store.getters.routePrefix,
- 'userInfo'
- )
- self.$store.dispatch('user/logout')
- if (result === 'confirm') {
- // redirect(self.$store.getters.routePrefix)
- self.$router.replace(self.$store.getters.routePrefix)
- }
- return
- }
- }
- const res = await data.blob()
- const link = document.createElement('a')
- const url = URL.createObjectURL(res)
- link.href = url
- link.download = fileName
- link.click()
- console.log(url)
- URL.revokeObjectURL(url)
- } catch (err) {
- self.$message.error(`下载${fileName}失败`)
- console.log(err)
- } finally {
- clearInterval(tiemer)
- progressRef.percentage = 100
- notification && notification.close()
- }
- }
- // 通过链接下载
- export default function downloadFile(downUrl, fileName, self, $event) {
- if (isWeChat()) {
- // 加密下载链接
- const data = {
- downUrl: downUrl,
- token: self.$store.getters.accessToken,
- fileName: fileName,
- }
- const redirectUrl = `${
- process.env.LOCALHOSE
- }/public/download?state=${encodeURIComponent(encrypt(data))}`
- return handleClipboard(
- redirectUrl,
- $event,
- '下载链接已复制到剪切板,请粘贴到浏览器中下载'
- )
- } else {
- downloadWithUrl(downUrl, fileName, self)
- }
- }
|