前端代码:
import axios from 'axios';
downloadReport(fileid, filename) {
if (filename !== null) {
axios.get('/xxx/xxx/xxx', {
params: {
fileid: fileid - 0
},
responseType: 'blob',
headers: {
'content-disposition': 'attachment;filename=docx', // filename为下载类型
'content-type': 'application/msword;charset=utf-8'
}
}).then(res => {
debugger;
const url = window.URL.createObjectURL(res.data);
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
});
} else {
this.$message({
message: '暂无报告',
type: 'error'
});
}
}
后端代码:
@RequestMapping(value = "/downloadById", method = RequestMethod.GET)
public void downloadById(HttpServletResponse response, Integer fileid) {
try {
String filePath = StringUtils.EMPTY;
// String realPath = request.getSession().getServletContext().getRealPath("/");
// realPath = new File(realPath).getParent();
// 根据文件ID查询到对应的文件
FileInfoVO fileInfoVO = fileInfoService.selectByPrimaryKey(fileid);
if (fileInfoVO != null) {
filePath = fileInfoVO.getFilepath();
}
ServletOutputStream outputStream = response.getOutputStream();
// filePath = realPath + File.separator + filePath;
// 创建流对象
File file = new File(filePath);
if (!file.exists()) {
byte[] b = "文件不存在,请重新上传!".getBytes("GBK");
InputStream input = new ByteArrayInputStream(b);
input.read(b);
outputStream.write(b);
input.close();
outputStream.flush();
return;
}
String downloadFileName = fileInfoVO.getOrgfilename();
// 写明要下载的文件的大小
response.setContentLength((int) file.length());
// URLEncoder.encode(downloadFileName,
// "UTF-8").replaceAll("\\+","%20"))
// 转码汉字并去掉文件名中包含的. 空格等特殊字符还原成原始文件名
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(downloadFileName, "UTF-8").replaceAll("\\+", "%20"));// 设置在下载框默认显示的文件名
response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
// 读出文件到response
// 这里是先需要把要把文件内容先读到缓冲区
// 再把缓冲区的内容写到response的输出流供用户下载
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] b = new byte[bufferedInputStream.available()];
outputStream.flush();
bufferedInputStream.read(b);
outputStream.write(b);
bufferedInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}