摘要:當後台返回一個文件地址給前端,需要前端下載並重命名,展示下載進度。
使用技術: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'
// 當請求被髮送到服務器時,我們需要執行一些基於響應的任務。
// 每當 readyState 改變時,就會觸發 onreadystatechange 事件。
// onreadystatechange存儲函數(或函數名),每當 readyState 屬性改變時,就會調用該函數。
// readyState
// 存有 XMLHttpRequest 的狀態。從 0 到 4 發生變化。
// 0: 請求未初始化
// 1: 服務器連接已建立
// 2: 請求已接收
// 3: 請求處理中
// 4: 請求已完成,且響應已就緒
// 用true時,表示發送異步請求,請規定在響應處於 onreadystatechange 事件中的就緒狀態時執行的函數:
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()
})
}