import axios from 'axios'
import { getToken } from '@/utils/auth'
const mimeMap = {
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
zip: 'application/zip'
}
const baseUrl = process.env.VUE_APP_BASE_API
export function downloadExcel(str, type="xlsx", filename) {
axios({
method: 'get',
url: baseUrl + str,
responseType: 'blob',
headers: { 'Authorization': 'Bearer ' + getToken() }
}).then(res => {
resolveBlob(res, mimeMap[type])
})
}
/**
* 解析blob响应内容并下载
* @param {*} res blob响应内容
* @param {String} mimeType MIME类型
*/
export function resolveBlob(res, mimeType) {
var blob = new Blob([res.data], { type: mimeType });
//从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.xlsx") 设置的文件名;
var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
var contentDisposition = decodeURI(res.headers['content-disposition']);
var result = patt.exec(contentDisposition);
var fileName = result[1];
fileName = fileName.replace(/\"/g, '');
const ObjectUrl = URL.createObjectURL(blob);
// 对于<a>标签,只有 Firefox 和 Chrome(内核)支持 download 属性
if ('download' in document.createElement('a')) {
const aLink = document.createElement('a');
aLink.href = ObjectUrl;
aLink.setAttribute('download', fileName) // 设置下载文件名称
document.body.appendChild(aLink)
aLink.click()
window.URL.revokeObjectURL(ObjectUrl) // 释放URL 对象
} else {
// IE 浏览器兼容方法
window.navigator.msSaveBlob(blob, fileName)
}
}
备注:本质还是拿到后台的文件流数据,然后前端转成二进制文件,通过a标签的download属性来下载
相关文章
暂无评论...