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下載

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章