使用示例:
import { fileDownload } from '@/utils/fileDownload'fileDownload({ url: process.env.VUE_APP_BASE_URL + `/statistic/pageList/export`, method: 'post', data: data })
工具类:
import store from '../store/index'
import {getAccessToken
} from '@/utils'
import axios from 'axios'
const token = store.getters.token || getAccessToken()
// 单个文件下载
export const fileDownload = (obj) => {let axiosParams = {method: obj.method,url: process.env.VUE_APP_apipath + obj.url,responseType: 'blob',headers: {'Authorization': `Bearer ${token}`}}if (obj.method && 'POST' === obj.method.toUpperCase()) {axiosParams.data = obj.data ? obj.data : {}}if (obj.method && 'GET' === obj.method.toUpperCase()) {axiosParams.params = obj.params ? obj.params : {}}return axios(axiosParams).then(res => {if (res && res.data) {const url = window.URL.createObjectURL(new Blob([res.data], {type: 'application/octet-stream'}))if (obj.noLink) {return url}const link = document.createElement('a')link.style.display = 'none'link.href = urlif (res.headers['content-disposition']) {console.log(decodeURI(res.headers['content-disposition'].slice(res.headers['content-disposition'].indexOf('=') + 1,res.headers['content-disposition'].indexOf('.'))))link.download =decodeURI(res.headers['content-disposition'].slice(res.headers['content-disposition'].indexOf('=') + 1,res.headers['content-disposition'].indexOf('.'))) +res.headers['content-disposition'].slice(res.headers['content-disposition'].indexOf('.'))} else {if (obj.fileName) {link.download = obj.fileName}}document.body.appendChild(link)link.click()window.URL.revokeObjectURL(url)}})
}
后端返回设置: