Vue文件下载进度条的实现过程

 更新时间:2022年07月05日 09:58:08   作者:高蓓蓓  
这篇文章主要介绍了Vue文件下载进度条的实现原理,通过使用onDownloadProgress方法API获取进度及文件大小等数据,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

需求场景:

1、大文件压缩过后依旧很大,接口返回response速度过慢,页面没有任何显示,体验太差。

2、需要在浏览器显示正在加载中的状态优化显示,提高用户体验

实现原理:

1、使用onDownloadProgress方法API获取进度及文件大小等数据

2、mixin混入实现监听进度条进度

3、vuex修改进度条进度

优化过程:

使用onDownloadProgress封装一个下载文件的方法

downFileProgress: function (url, params, headers, blenderApiUrl, callback, uniSign) {
   return axios({
     url: url,
     params: params,
     method: 'get',
     responseType: 'blob',
     baseURL: blenderApiUrl,
     headers: headers,
     onDownloadProgress (progress) {
       callback(progress, uniSign)
     }
   })
 }

在下载文件的地方,使用封装的方法downFileProgress

downOrgFile (row) {
  let uniSign = `${new Date().getTime()} ` // 可能会连续点击下载多个文件,这里用时间戳来区分每一次下载的文件
  const url = `${this.$api.LifeInsuranceScenario2DownFile}/${row.account_name}/${row.task_id}`
  const baseUrl = this.iframeData.blenderApiUrl
  this.$http.downFileProgress(url, {}, this.headers, baseUrl, this.callBackProgress, uniSign).then(res => {
    if (!res) {
      this.$sweetAlert.errorWithTimer('文件下载失败!')
      return
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([res.data]), '中间项下载.zip')
    } else {
      let url = window.URL.createObjectURL(new Blob([res.data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', 'xxx.zip')
      document.body.appendChild(link)
      link.click()
      link.remove()
    }
  })
},
callBackProgress (progress, uniSign) {
  let total = progress.srcElement.getResponseHeader('Real-Content-Length')
  // progress对象中的loaded表示已经下载的数量,total表示总数量,这里计算出百分比
  let downProgress = Math.floor((progress.loaded / total) * 100)
  // 将此次下载的文件名和下载进度组成对象再用vuex状态管理
  this.$store.commit('SET_PROGRESS', { path: uniSign, progress: downProgress })
}

创建component同等级mixin文件夹,文件夹创建index.js

import { mapState } from 'vuex'
export const mixins = {
  computed: {
    ...mapState({
      progressList: state => state.progressList
    })
  },
  data () {
    return {
      notify: {} // 用来维护下载文件进度弹框对象
    }
  },
  watch: {
    // 监听进度列表
    progressList: {
      handler (n) {
        let data = JSON.parse(JSON.stringify(n))
        data.forEach(item => {
          const domList = [...document.getElementsByClassName(item.path)]
          if (domList.find(i => i.className === item.path)) {
            // 如果页面已经有该进度对象的弹框,则更新它的进度progress
            if (item.progress) domList.find(i => i.className === item.path).innerHTML = item.progress + '%'
            if (item.progress === null) {
              // 此处容错处理,如果后端传输文件流报错,删除当前进度对象
              this.$store.commit('DEL_PROGRESS', item.path)
              this.$notify.error({ title: '错误', message: '文件下载失败!' })
            }
          } else {
            // 如果页面中没有该进度对象所对应的弹框,页面新建弹框,并在notify中加入该弹框对象,属性名为该进度对象的path(上文可知path是唯一的),属性值为$notify(element ui中的通知组件)弹框对象
            this.notify[item.path] = this.$notify.success({
              dangerouslyUseHTMLString: true,
              customClass: 'progress-notify',
              message: `<p style="width: 150px;line-height: 13px;">中间项正在下载<span class="${item.path}" style="float: right">${item.progress}%</span></p>`, // 显示下载百分比,类名为进度对象的path(便于后面更新进度百分比)
              showClose: true,
              duration: 0
            })
          }
          if (item.progress === 100) {
            // 如果下载进度到了100%,关闭该弹框,并删除notify中维护的弹框对象
            // this.notify[item.path].close()
            // 上面的close()事件是异步的,直接delete this.notify[item.path]会报错,利用setTimeout,将该操作加入异步队列
            setTimeout(() => {
              delete this.notify[item.path]
            }, 1000)
            this.$store.commit('DEL_PROGRESS', item.path) // 删除caseInformation中state的progressList中的进度对象
          }
        })
      },
      deep: true
    }
  }
}

下载方法的组件引入mixin

import { mixins } from '../mixin/index'
export default {
  mixins: [mixins],
  ......
}

Vuex配置进度条

const state = {
  progressList: []
}
export default state
const mutations = {
  SET_PROGRESS: (state, progressObj) => {
    // 修改进度列表
    if (state.progressList.length) {
      // 如果进度列表存在
      if (state.progressList.find(item => item.path === progressObj.path)) {
        // 前面说的path时间戳是唯一存在的,所以如果在进度列表中找到当前的进度对象
        state.progressList.find(item => item.path === progressObj.path).progress = progressObj.progress
        // 改变当前进度对象的progress
      }
    } else {
      // 当前进度列表为空,没有下载任务,直接将该进度对象添加到进度数组内
      state.progressList.push(progressObj)
    }
  },
  DEL_PROGRESS: (state, props) => {
    state.progressList.splice(state.progressList.findIndex(item => item.path === props), 1) // 删除进度列表中的进度对象
  },
  CHANGE_SETTING: (state, { key, value }) => {
    // eslint-disable-next-line no-prototype-builtins
    if (state.hasOwnProperty(key)) {
      state[key] = value
    }
  }
}

export default mutations
export const getProgressList = state => state.progressList
export const changeSetting = function ({ commit }, data) {
  commit('CHANGE_SETTING', data)
}
export const setprogress = function ({ commit }, data) {
  commit('SET_PROGRESS', data)
}
export const delprogress = function ({ commit }, data) {
  commit('DEL_PROGRESS', data)
}

最终效果图

参考文章:

juejin.cn/post/702437…

到此这篇关于Vue文件下载进度条的实现过程的文章就介绍到这了,更多相关Vue下载进度条内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 在vue项目中优雅的使用SVG的方法实例详解

    在vue项目中优雅的使用SVG的方法实例详解

    本文旨在介绍如何在项目中配置和方便的使用svg图标。本文以vue项目为例给大家介绍在vue项目中优雅的使用SVG的方法,需要的朋友参考下吧
    2018-12-12
  • vue3限制table表格选项个数的解决方法

    vue3限制table表格选项个数的解决方法

    这篇文章主要为大家详细介绍了vue3限制table表格选项个数的解决方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04
  • Vue中key为index和id的区别示例详解

    Vue中key为index和id的区别示例详解

    这篇文章主要介绍了Vue中key为index和id的区别详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-06-06
  • vue改变数据后数据变化页面不刷新的解决方法

    vue改变数据后数据变化页面不刷新的解决方法

    这篇文章主要给大家介绍了关于vue改变数据后数据变化页面不刷新的解决方法,vue比较常见的坑就是数据(后台返回)更新了,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-07-07
  • Vue中 Vue.prototype使用详解

    Vue中 Vue.prototype使用详解

    本文将结合实例代码,介绍Vue中 Vue.prototype使用,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
    2021-07-07
  • Vue3中使用i18n,this.$t报错问题及解决

    Vue3中使用i18n,this.$t报错问题及解决

    这篇文章主要介绍了Vue3中使用i18n,this.$t报错问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04
  • 详解VUE调用本地json的使用方法

    详解VUE调用本地json的使用方法

    这篇文章主要介绍了VUE调用本地json的使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-05-05
  • 基于vue.js实现侧边菜单栏

    基于vue.js实现侧边菜单栏

    这篇文章主要为大家详细介绍了基于vue.js实现侧边菜单栏的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-03-03
  • 使用vue for时为什么要key【推荐】

    使用vue for时为什么要key【推荐】

    很多朋友不明白在使用vue for时为什么要key,key的作用有哪些,在文中给大家详细介绍,需要的朋友可以参考下
    2019-07-07
  • vue3中引入svg矢量图的实现示例

    vue3中引入svg矢量图的实现示例

    在项目开发过程中,我们经常会用到svg矢量图,本文主要介绍了vue3中引入svg矢量图的实现示例,具有一定的参考价值,感兴趣的可以了解一下
    2023-11-11

最新评论