关于vue.js:vue项目下载文件重命名监测进度

摘要:当后盾返回一个文件地址给前端,须要前端下载并重命名,展现下载进度。
应用技术:ajax、blob、vue插件file-saver

1、插件

咱们不做过多解释,咱们这里只是应用,这是插件教程地址:http://vuejscomponent.com/pac…

2、我的项目代码

import FileSaver from 'file-saver'
// URL:文件寄存地址,fileName:保留文件名称,downloadType:保留文件格式
const singleFileDownload = (url, fileName, downloadType) => {
  return new Promise((resolve, reject) => {
    if (!url || !fileName) {
      reject('文件不存在')
      return
    }
    var xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.responseType = 'blob'
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200 || xhr.status === 0) {
          let file = null
          if (downloadType === 'pdf') {
            file = new Blob([xhr.response], { type: "application/pdf" });
          } else {
            file = new Blob([xhr.response], { type: "application/zip" });
          }
          FileSaver.saveAs(file, fileName)
          resolve('下载胜利')
        } else {
          reject(new Error(fileName + '下载失败'), null)
        }
      }
    }
    xhr.addEventListener('progress', (e) => {
      // e.total就是文件的总字节 e.loaded就是文件已加载了多少字节了
      // downloadFile.progress = (e.loaded * 1.0 / e.total * 100).toFixed(2) + '%'
      // downloadFile.progress = (e.loaded / (1024 * 1024)).toFixed(2) + 'M/' + (e.total / (1024 * 1024)).toFixed(2) + 'M'
    })
    xhr.send()
  })
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理