js實現(xiàn)下載(文件流式)方法詳解與完整實例源碼
在介紹JS文件流式下載文件方法之前,先記錄下window.location.href的使用方法
window.location.href的用法
javascript中的location.href有很多種用法,主要如下。
self.location.href="/url"http://當前頁面打開URL頁面 location.href="/url"http://當前頁面打開URL頁面 windows.location.href="/url" //當前頁面打開URL頁面,前面三個用法相同。 this.location.href="/url" //當前頁面打開URL頁面 parent.location.href="/url" // 在父頁面打開新頁面 top.location.href="/url" //在頂層頁面打開新頁面
如果頁面中自定義了frame,那么可將parent self top換為自定義frame的名稱,效果是在frame窗口打開url地址
此外,window.location.href=window.location.href;和window.location.Reload()和都是刷新當前頁面。區(qū)別在于是否有提交數(shù)據(jù)。
當有提交數(shù)據(jù)時,window.location.Reload()會提示是否提交,window.location.href=window.location.href;則是向指定的url提交數(shù)據(jù)
JS文件流式下載文件源碼實例
下面是使用axios寫的一個完整JS文件流式下載文件的完整源碼
const apiurl = '' // 接口地址
this.exportLoading = true
axios.post(apiurl, params, {
'responseType': 'blob' //設置響應的數(shù)據(jù)類型為一個包含二進制數(shù)據(jù)的 Blob 對象,必須設置?。?!
}).then( (response) =>{
console.log('response', response, response.data.size)
this.exportLoading = false
if(response.data){
if(response.data.size < 1000){
// 根據(jù)文件流的大小判斷異常情況
if(response.data.size == 63){
this.$message.warning('查無結果');
return
}
if(response.data.size == 84){
this.$message.warning('導出數(shù)據(jù)超出最大限制值');
return
}
}else{
const blob = new Blob([response.data],{type: 'application/vnd.ms-excel'})
const linkNode = document.createElement('a');
linkNode.style.display = 'none';
linkNode.href = URL.createObjectURL(blob); //生成一個Blob URL
document.body.appendChild(linkNode);
linkNode.click(); //模擬在按鈕上的一次鼠標單擊
URL.revokeObjectURL(linkNode.href); // 釋放URL 對象
document.body.removeChild(linkNode);
}
}
}).catch( (error) =>{
console.log(error);
this.exportLoading = false
});相關文章
JavaScript與Div對層定位和移動獲得坐標的實現(xiàn)代碼
JavaScript與Div對層定位和移動獲得坐標的實現(xiàn)代碼,需要的朋友可以參考下。2010-09-09
uniapp uni-swipe-action 滑動操作狀態(tài)恢復功能實現(xiàn)
按照uni-app官方文檔的寫法,當前一條滑動確認之后頁面列表刷新但是滑動的狀態(tài)還在,我們需要在滑動確認之后 頁面刷新 滑動狀態(tài)恢復,下面小編給大家分享uniapp uni-swipe-action 滑動操作狀態(tài)恢復功能實現(xiàn),感興趣的朋友跟隨小編一起看看吧2024-06-06

