Javascript前端下載后臺(tái)傳來(lái)的文件流代碼實(shí)例
前臺(tái)請(qǐng)求數(shù)據(jù):
url: ’/app/downloadApp’, method: ’get’, responseType: ’blob’, params: data
設(shè)置接收參數(shù)格式為responseType: ‘blob’,
downloadFile(res, fileName) { if (!res) { return } if (window.navigator.msSaveBlob) { // IE以及IE內(nèi)核的瀏覽器 try { window.navigator.msSaveBlob(res, fileName) // res為接口返回?cái)?shù)據(jù),這里請(qǐng)求的時(shí)候已經(jīng)處理了,如果沒(méi)處理需要在此之前自行處理var data = new Blob([res.data]) 注意這里需要是數(shù)組形式的,fileName就是下載之后的文件名 // window.navigator.msSaveOrOpenBlob(res, fileName); //此方法類似上面的方法,區(qū)別可自行百度 } catch (e) { console.log(e) } } else { let url = window.URL.createObjectURL(new Blob([res])) let link = document.createElement(’a’) link.style.display = ’none’ link.href = url link.setAttribute(’download’, fileName)// 文件名 document.body.appendChild(link) link.click() document.body.removeChild(link) // 下載完成移除元素 window.URL.revokeObjectURL(url) // 釋放掉blob對(duì)象 } }, download(){ var data = { appId:this.appId } downloadAppAjax(data).then(res => { const filename = decodeURI(res.headers[’content-disposition’].split(’;’)[1].split(’=’)[1]); console.log(filename) this.downloadFile(res.data,filename) }) }
這里的downloadAppAjax調(diào)用后臺(tái)接口,請(qǐng)求數(shù)據(jù),獲取后臺(tái)返回的數(shù)據(jù)沒(méi)有文件名,最后發(fā)現(xiàn)在header Content-Disposition屬性里 attachment;filename=app.jpg
所以我們要實(shí)現(xiàn)下載自動(dòng)重命名就需要拿出filename,這里我們使用decodeURI對(duì)Content-Disposition屬性值進(jìn)行解碼,拿到filename:
decodeURI(res.headers[’content-disposition’].split(’;’)[1].split(’=’)[1]);
拿到文件流和文件名后 接收文件流并創(chuàng)建地址
let url =window.URL.createObjectURL(new Blob([res]))
接著利用a標(biāo)簽進(jìn)行下載即可。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. idea給項(xiàng)目打war包的方法步驟2. 兩行Javascript代碼生成UUID的方法3. php操作redis常見(jiàn)方法示例【key與value操作】4. Python importlib模塊重載使用方法詳解5. PHP代碼加密的方法總結(jié)6. 解決Android Studio XML編輯界面不顯示下面的Text和Design選項(xiàng)卡7. PHP的curl常用的5個(gè)例子8. PHP網(wǎng)頁(yè)UTF8編碼開(kāi)發(fā)中空白的問(wèn)題9. 在Android環(huán)境下WebView中攔截所有請(qǐng)求并替換URL示例詳解10. Spring下Filter過(guò)濾器配置全局異常處理的詳細(xì)步驟
