JS下載檔案兩種方式
阿新 • • 發佈:2021-06-16
JS下載檔案兩種方式
-
態靜態資源下載,直接
window.location.href=URL
或window.open(URL)
或 建立 a 標籤並指定a.href=URL
模擬點選進行下載 -
另外一種則是二進位制下載檔案,首先將
XMLHttpRequest.responseType
設定為blob
,然後用URL.createObjectURL()
和Blob
處理返回二進位制流,然後使用 a 標籤進行下載
// 這裡採用Axios.js做請求 // Axios Docs:https://www.runoob.com/vue2/vuejs-ajax-axios.html export function downloadExcel({method = 'GET', url, responseType = 'blob', params, data, fileName = '表格', suffix = 'xlsx'}) { const option = {method, responseType, url} if (method === 'GET') { option.params = params } else if (method === 'POST') { option.data = data } // request(option).then((response) => { axios(option).then((response) => { // 判斷介面是否正常響應了二進位制流,沒有則拋錯 if (!response || response.msg) { return alert(response.msg || '介面未響應訊息') } // 如果支援微軟的檔案下載方式(ie10+瀏覽器) if (window.navigator.msSaveBlob) { try { // 只要顯示下載欄,就是返回true,若果失敗則返回false navigator.msSaveBlob(new Blob([response]), `${fileName}.${suffix}`) } catch (e) { console.log(e) } } else { // 相容不同瀏覽器的URL物件 const URL = window.URL || window.webkitURL || window.moxURL; // 建立下載連結,直接使用響應頭中的type,就是檔案字尾名 const href = URL.createObjectURL(new Blob([response], {type: response.type})) // 建立a標籤併為其新增屬性 const a = document.createElement('a') a.href = href a.download = `${fileName}.${suffix}` document.body.appendChild(a) a.click() //觸發點選事件執行下載 a.style.dispaly = 'none' const timer = setTimeout(function () { a.remove() // document.body.removeChild(a) // 釋放blob物件 URL.revokeObjectURL(href) clearTimeout(timer) }, 1000) } }) }
網站資源
URL.createObjectURL:https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
Blob:https://developer.mozilla.org/zh-CN/docs/Web/API/Blob
responseType:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/responseType
msSaveBlob:https://developer.mozilla.org/en-US/docs/Web/API/Navigator/msSaveBlob