vue使用blob下載文件遇到的問題小結(jié)
Blob 對(duì)象表示一個(gè)不可變、原始數(shù)據(jù)的類文件對(duì)象。它的數(shù)據(jù)可以按文本或二進(jìn)制的格式進(jìn)行讀取。
在項(xiàng)目中遇到需求,需要將后端返回的二進(jìn)制流下載成 excel 表格形式,首先,先寫一個(gè)方法用來下載
export function fileDownload(res) { let blob = new Blob([res.data], { type: res.data.type, }) let downloadElement = document.createElement('a') let href = window.URL.createObjectURL(blob) //創(chuàng)建下載鏈接 let fileName = res.headers['content-disposition'] ? res.headers['content-disposition'].split('attachment;filename=')[1] : new Date().getTime() downloadElement.href = href // window.open(downloadElement.href) downloadElement.download = decodeURIComponent(fileName) //解碼 document.body.appendChild(downloadElement) downloadElement.click() document.body.removeChild(downloadElement) window.URL.revokeObjectURL(href) //釋放掉blob對(duì)象 }
當(dāng)然,也可以使用自定義的文件名,自己傳遞一個(gè)文件名即可
export function downloadFile(res, fileName) { const blob = new Blob([res.data], { type: res.data.type }) let dom = document.createElement('a') let url = window.URL.createObjectURL(blob) dom.href = url dom.download = decodeURI(fileName) dom.style.display = 'none' document.body.appendChild(dom) dom.click() dom.parentNode.removeChild(dom) window.URL.revokeObjectURL(url) }
需要注意的是,要記得在下載接口的地方加上 responseType: 'blob',
切記,一定要加上 responseType: 'blob', 否則下載的會(huì)亂碼甚至讀取不出來
加上之后,在需要使用的地方使用即可
async handleSubmit() { if (this.form.pushDepartment.length === 0) { this.$message.warning(`推送部門不能為空`) return false } // 導(dǎo)出excel表格 let params = { healthCodeAlarmIds: [], sendDepartment: [], } this.selectData.forEach((item) => { let id = parseInt(item.id) params.healthCodeAlarmIds.push(id) }) params.sendDepartment = this.form.pushDepartment let res = await exportInfo({ ...params }) // console.log('res', res) fileDownload(res) // downloadFile(res, 'yj.xlsx') },
到此這篇關(guān)于vue使用blob下載文件遇到的問題的文章就介紹到這了,更多相關(guān)vue blob下載文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue el-date-picker 開始日期不能大于結(jié)束日期的實(shí)現(xiàn)代碼
這篇文章主要介紹了vue el-date-picker 開始日期不能大于結(jié)束日期的實(shí)現(xiàn)代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-01-01vue中如何實(shí)現(xiàn)pdf文件預(yù)覽的方法
這篇文章主要介紹了vue中如何實(shí)現(xiàn)pdf文件預(yù)覽的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07Vue3+Vite項(xiàng)目使用less的實(shí)現(xiàn)步驟
最近學(xué)習(xí)在vite項(xiàng)目中配置less,本文主要介紹了Vue3+Vite項(xiàng)目使用less的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-02-02羊了個(gè)羊通關(guān)腳本Vue?node實(shí)現(xiàn)版本
這篇文章主要為大家介紹了羊了個(gè)羊通關(guān)腳本Vue?node實(shí)現(xiàn)版本,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09