axios用get或post請求下載文件,可下載原來的文件名


一、get請求下載:

window.open(url, params)

 

二、post請求下載

創建一個a標簽下載
axios({ url: url, method:
'post', data: data, responseType: 'blob' }).then(res => { let blob = new Blob([res.data]) let url = window.URL.createObjectURL(blob) let link = document.createElement('a') link.style.display = 'none' link.href = url // 文件名一般是在res.headers里:content-disposition;fileName=xxxxxxxxxx.csv,這個讓后端統一規定文件名怎么放前端就怎么取就行 let str = typeof res.headers['content-disposition'] === 'undefined' ? res.headers['Content-Disposition'].split(';')[1] : res.headers['content-disposition'].split(';')[1] let filename = typeof str.split('fileName=')[1] === 'undefined' ? str.split('filename=')[1] : str.split('fileName=')[1] link.setAttribute('download', decodeURIComponent(filename)) // 解碼,這里也可以自定義下載的文件名字,如link.setAttribute('download', 'xxxxxdownload.xls') document.body.appendChild(link) link.click() //用新窗口打開window.open(link.click()),但是下載完成后不會先get請求那樣自動關閉窗口 }) .catch(error => { console.log(error) })

 

用哪種方式下載:

1)下載文件比較大建議使用get。如果用post,點了會半天沒反應,得加loading之類的而且體驗也不好,用get在用window.open打開新窗口下載,下載完后會自動關閉窗口體驗比較好

2)下載文件不大而且傳參很多的話建議使用post。不過只能在本頁面下載,不能打開新窗口下載,哪怕把數據放到window.open打開新窗口下載,但下載完成后不會自動關閉新窗口

3)下載文件很大而且傳參也很大建議用get,傳參過長超過瀏覽器限制,那讓后台再加一個post接口,把這些多的參數用這個post傳過去,再回傳一下類似秘鑰之類的用於get下載

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM