axios 请求文件
axios 请求文件
前端代码:
downloadFile (fileId) {
// 自己的环境变量
var path = process.env.REPORT_API
axios({
url: path + '/file/downloadFile/' + fileId + '?access_token=' + getToken(),
method: 'get',
// data: this.pptFormInfo,
responseType: 'blob'
}).then(response => {
const blob = new Blob([response.data])
// 从响应头中获取文件名字
let contentDisposition = response.headers['content-disposition']
let patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
let fileName = escape(patt.exec(contentDisposition)[1])
// 对文件名字进行解码防止中文名乱码
fileName = decodeURI(fileName)
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
// 释放掉blob对象
URL.revokeObjectURL(elink.href)
// 下载完成移除元素
document.body.removeChild(elink)
})
}
后端代码:
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
// 通知浏览器进行文件下载
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF8"));
// 暴露header 方便前端获取文件名字
response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(file);
outputStream.close();