跨域將blob物件儲存到本地
阿新 • • 發佈:2021-06-11
應用場景
專案前後端分離,後端環境Django. 需要實現 前端可以下載後端生成的EXCEL檔案同時對許可權進行控制。
將blob儲存到本地
function saveAs(blob,fileName) { if ('download' in document.createElement('a')) { // 不是IE瀏覽器 let url = window.URL.createObjectURL(blob) let link = document.createElement('a') link.style.display= 'none' link.href = url link.setAttribute('download', fileName) document.body.appendChild(link) link.click() document.body.removeChild(link) // 下載完成移除元素 window.URL.revokeObjectURL(url) // 釋放掉blob物件 } else{ // IE 10+ window.navigator.msSaveBlob(blob, fileName) } }
獲取blob內容,同樣支援GET\POST獲取
var xmlhttp xmlhttp = new XMLHttpRequest() xmlhttp.onreadystatechange = function () { // Call a function when the state changes. if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { // Request finished. Do processing here. console.log(xmlhttp.response) saveAs(xmlhttp.response, 'filename.xlsx') } } // async=false -同步,ture 非同步 xmlhttp.open(method='GET',url='http://ctcnc0378.carsgen.com:8000/budget/file_download?period_id=15', async=true) xmlhttp.setRequestHeader('Content-type', 'application/octet-stream') // 設定跨域訪問的Token頭 xmlhttp.setRequestHeader('Authorization', 'Token 8002f4d3e770ada98ef5360c32e59d24f74b12cb') xmlhttp.withCredentials = true xmlhttp.responseType = "blob"; xmlhttp.send(null)
也可以用axios獲取
axios({ method: 'post', url: 'api/user/', data: { period: '2021' }, responseType: 'blob' }).then(response => { saveAs(response) }).catch((error) => { })