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

更优雅的下载文件方式:前端异步下载文件程序的实现

最编程 2024-06-26 21:55:03
...
// 需要注意下载 excel 时, axios 或 xhr 请求需要将 xhr.responseType = "blob" // 否则下载后的 excel 会打不开 // 返回类型blob downloadExcel (params) { // 封装过的 axios this.$api.downloadExcel(params).then(res => { let filename = res.headers['filename'] // const blob = new Blob([res.data]) // 将字符流转换为 blob对象 blobDownload(res.data, decodeURIComponent(filename)) }).finally(() => { this.loading = false }) }, /** * 下载文件:下载 blob 对象形式的文件 * @param blob * @param filename */ export function blobDownload (blob, filename = '文件.txt') { let url = window.URL.createObjectURL(blob) // 解决 ie 不支持直接下载 blob资源 if ('msSaveOrOpenBlob' in navigator) { window.navigator.msSaveOrOpenBlob(blob, filename) return } let link = document.createElement('a') link.style.display = 'none' link.href = url link.download = filename document.body.appendChild(link) link.click() document.body.removeChild(link) // 下载完成移除元素 window.URL.revokeObjectURL(url) // 释放掉blob对象 } // 创建axios实例 const service = axios.create({ headers: { 'kms-token': localStorage.getItem('token') || '' }, baseURL: config.ip, timeout: 2 * 600000, withCredentials: true // 表示跨域请求时是否需要使用凭证,开启后,后端服务器要设置允许开启 }) // request拦截器 service.interceptors.request.use( config => { const token = localStorage.getItem('token') if (config.url === '/api/excel/upload/knowledge/download') { // 返回类型blob,不设置会打不开 excel config.responseType = 'blob' // config.headers['Content-Type'] = 'application/x-download' } return config }, error => { // console.warn(error) return Promise.reject(error) } )

推荐阅读