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

5次阅读

共计 1009 个字符,预计需要花费 3 分钟才能阅读完成。

摘要:当后盾返回一个文件地址给前端,须要前端下载并重命名,展现下载进度。
应用技术: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()})
}
正文完
 0