欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

js 文件下载 blob

最编程 2024-07-17 13:42:25
...
// 判断是否有这个属性 const createObjectURL = function (object) { return window.URL ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object) } // 使用promise判断是否是文件流 const checkBlob = function (blob) { return new Promise<void>((resolve, reject) => { const fileReader = new FileReader() fileReader.onload = function (res: any) { const data = res.target.result.substr(0, 1) == '{' ? JSON.parse(res.target.result) : { success: true } if (!data.success) { reject(data.msg) } else { resolve() } } fileReader.readAsText(blob) }) } // 文件下载的主体方法 // callback是文件下载成功后的回调函数 // app.config.globalProperties.blobFileDownLoad = function ( params, callback ) { if (!params.method) params.method = 'get' const xhr = new XMLHttpRequest() xhr.open(params.method, params.url, true) xhr.setRequestHeader( 'Authorization', 'Bearer ' + store.state.login.accessToken ) xhr.responseType = 'blob' xhr.onload = function (e) { if (this.status == 200) { const blob = this.response checkBlob(blob) .then(() => { const filename = params.name + '.xls' const _window: any = window if (_window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename) } else { const a = document.createElement('a') const url = createObjectURL(blob) a.href = url a.download = filename document.body.appendChild(a) a.click() window.URL.revokeObjectURL(url) } }) .catch(err => { window.$message.error(err) }) callback() } } xhr.setRequestHeader('Content-type', 'application/json') xhr.send(params.data) }