vue文件下载mixin

78 阅读1分钟
import { downLoadFlie } from '@/API/api_cet_qualifications.js'
import { downAddFileWaterMark } from '@/API/api_cet_record.js'

export default {

  data() {

    return {

      fileUrl'',

      isDownloadingfalse,

    }

  },

  computed: {

  },

  methods: {

    downUopFileBlob(url, filename) {

      this.getUopFileBlob(url).then((blob) => {

        this.saveUopFileAs(blob, filename)

      })

    },

    getUopFileBlob(url) {

      return new Promise((resolve) => {

        const xhr = new XMLHttpRequest()

        xhr.open('GET', url, true)

        xhr.responseType = 'blob'

        xhr.onload = () => {

          if (xhr.status === 200) {

            resolve(xhr.response)

          }

        }

  


        xhr.send()

      })

    },

    saveUopFileAs(blob, filename) {

      if (window.navigator.msSaveOrOpenBlob) {

        navigator.msSaveBlob(blob, filename)

      } else {

        const link = document.createElement('a')

        const body = document.querySelector('body')

  


        link.href = window.URL.createObjectURL(blob)

        link.download = filename

        // fix Firefox

        link.style.display = 'none'

        body.appendChild(link)

  


        link.click()

        body.removeChild(link)

  


        window.URL.revokeObjectURL(link.href)

      }

    },

    async downloadUopFile(fileId, fileName, isWatermark = false) {

      if (!fileId) return this.$message.error('无FileId, 下载失败')

      if (this.isDownloading === truereturn false

      let res

      this.isDownloading = true

      res = await downLoadFlie({ fileId })

      try {

        if (res.err.errcode === 1) {

          if (isWatermark === true) {

            let res2 = await downAddFileWaterMark({

              fileId: fileId,

              fileName: fileName,

            })

            this.isDownloading = false

            this.fileUrl = res2.data.fileUrl

            this.downUopFileBlob(this.fileUrl, fileName)

          } else {

            this.isDownloading = false

            this.fileUrl = res.data.fileUrl

            this.downUopFileBlob(this.fileUrl, fileName)

          }

        }

      } catch (error) {

        this.isDownloading = false

        console.log('downloadUopFile--error', error)

      }

    },

  }

}