跨域将blob对象保存到本地
应用场景
项目前后端分离,后端环境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) => { })