1. 上传
修改请求头
export function importFile (param) {
const config = {
// 添加请求头
headers: {
'Content-Type': 'multipart/form-data'
}
}
return axios.post('/importFile', param, config)
}
获取文件,用formData包装,调用接口
const element = document.getElementById('fileToUpload')
const files = element.files
const formData = new FormData()
const file = element.files[0]
formData.append('file', file)
importFile (formData).then(res => {
// ...
})
2. 下载
export function downloadFile (param) {
return axios.post('/downloadFile ',
qs.stringify(param, { indices: false }),
{
responseType: 'arraybuffer'
}
)
}
exportInfoResource(param).then(res => {
_this.handleExcelExportResult(res)
})
handleExcelExportResult (res) {
const blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' })
const downloadLink = document.createElement('a')
// 创建下载的链接
const href = window.URL.createObjectURL(blob)
downloadLink.href = href
// 下载后文件名, 返回res中只有二进制数据,获取不到header
// const disposition = res.headers['content-disposition']
// downloadLink.download = decodeURI(disposition.substring(disposition.indexOf('filename=') + 9, disposition.length))
downloadLink.download = moment(new Date()).format('YYYYMMDDhhmmss') + '.xls'
document.body.appendChild(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink)
// 释放掉blob对象
window.URL.revokeObjectURL(href)
},