import axios from 'axios'
|
import store from '@/store'
|
import { Message } from 'element-ui'
|
|
/**
|
*文件下载
|
*/
|
export function downloadFile (config, type = 'application/vnd.ms-excel') {
|
return axios({
|
method: config.Method ? 'get' : 'post',
|
url: `${process.env.VUE_APP_CURRENTMODE === 'development' ? '/api' : process.env.VUE_APP_API_BASE_URL}${config.url}`,
|
data: config.data, // 传递参数
|
params: config.Method ? config.data : undefined,
|
responseType: 'blob', // 表明返回服务器返回的数据类型
|
// 设置请求头信息
|
headers: {
|
Authorization: 'Bearer ' + store.state.token
|
},
|
// `onUploadProgress` 允许为上传处理进度事件
|
onUploadProgress: config.onUploadProgress,
|
onDownloadProgress: config.onDownloadProgress
|
}).then(response => {
|
if (!response.headers['content-disposition']) {
|
Message({
|
message: '导出失败!',
|
type: 'error'
|
})
|
return
|
}
|
return new Promise(function (resolve, reject) {
|
if (response.data) {
|
const blob = new Blob([response.data], { type })
|
const link = document.createElement('a')
|
link.style.display = 'none'
|
link.href = URL.createObjectURL(blob)
|
// response.headers['content-disposition'].split(';')[1].split('=')[1]
|
if (config.type !== 'varied') {
|
link.setAttribute('download', config.fileName + (config.type ? config.type : '.xls'))
|
} else {
|
link.setAttribute('download', config.fileName)
|
}
|
document.body.appendChild(link)
|
link.click()
|
document.body.removeChild(link)
|
resolve(1)
|
Message({
|
message: '导出成功!',
|
type: 'success'
|
})
|
} else {
|
reject(response.msg)
|
}
|
})
|
}).catch(error => {
|
Message({
|
message: '导出失败!',
|
type: 'error'
|
})
|
// 请求失败,
|
console.log(error)
|
})
|
}
|