js實現下載(文件流式)方法詳解與完整實例源碼
在介紹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ū)別在于是否有提交數據。
當有提交數據時,window.location.Reload()
會提示是否提交,window.location.href=window.location.href;
則是向指定的url提交數據
JS文件流式下載文件源碼實例
下面是使用axios
寫的一個完整JS文件流式下載文件的完整源碼
const apiurl = '' // 接口地址 this.exportLoading = true axios.post(apiurl, params, { 'responseType': 'blob' //設置響應的數據類型為一個包含二進制數據的 Blob 對象,必須設置?。?! }).then( (response) =>{ console.log('response', response, response.data.size) this.exportLoading = false if(response.data){ if(response.data.size < 1000){ // 根據文件流的大小判斷異常情況 if(response.data.size == 63){ this.$message.warning('查無結果'); return } if(response.data.size == 84){ this.$message.warning('導出數據超出最大限制值'); 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操作table(insertRow,deleteRow,insertCell,deleteCell方
本篇文章主要介紹了javascript操作table(insertRow,deleteRow,insertCell,deleteCell方法)需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12Javascript HTML5 Canvas實現的一個畫板
這篇文章主要為大家詳細介紹了Javascript HTML5 Canvas實現的一個畫板的相關資料,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-05-05JavaScript中字符串GBK與GB2312的編解碼示例講解
在瀏覽器JavaScript環(huán)境中,可以使用TextEncoder和TextDecoder?API?來進行?GBK?編碼和解碼,也可以使用?encodeURIComponent?函數對字符串進行編碼,最好使用第三方庫,比如iconv-lite來實現2023-12-12javascript:;與javascript:void(0)使用介紹
有時候我們在編寫js過程中,需要觸發(fā)事件而不需要返回值,那么就可能需要這樣的寫法2013-06-06