使用示例:
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 = url
if (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)
}
})
}
后端返回设置:
/**
* excel内容类型
*/
private static final String CONTENT_TYPE_EXCEL = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/**
* 编码
*/
private static final String ENCODE = "UTF-8";
/**
* Content-disposition
*/
private static final String CONTENT_DISPOSITION = "Content-disposition";
response.setContentType(CONTENT_TYPE_EXCEL);
response.setCharacterEncoding(ENCODE);
// 防止文件名的中文乱码
fileName = URLEncoder.encode(fileName, ENCODE).replaceAll("\\+", "%20");
response.setHeader(CONTENT_DISPOSITION, "attachment;filename=" + fileName + ".xlsx");