Javascript前端下載后臺(tá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)處理了,如果沒處理需要在此之前自行處理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ù)沒有文件名,最后發(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)行下載即可。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 使用Python webdriver圖書館搶座自動(dòng)預(yù)約的正確方法2. Python字符串到字節(jié)的轉(zhuǎn)換。雙反斜杠問題3. python 使用事件對(duì)象asyncio.Event來同步協(xié)程的操作4. Python 合并拼接字符串的方法5. Python sublime安裝及配置過程詳解6. Python3 json模塊之編碼解碼方法講解7. Linux刪除系統(tǒng)自帶版本Python過程詳解8. Java Long類型對(duì)比分析9. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條10. ASP基礎(chǔ)知識(shí)VBScript基本元素講解

網(wǎng)公網(wǎng)安備