文件下载
@ApiOperation(value = "文件下载")
@GetMapping("/download")
public void downLoad(HttpServletResponse response,@Validated @NotNull(message = "reportDailyDownloadReq not be null") ReportDailyDownloadReq reportDailyDownloadReq) {
ReportDaily reportDaily = reportDailyService.findReportDailyByDayStringAndReportId(new Date(reportDailyDownloadReq.getDay()), reportDailyDownloadReq.getReportId(),reportDailyDownloadReq.getReportFileTypeEnum());
if(null==reportDaily){
throw new BusinessException(RespCodeEnum.REPORT_DAILY_FILE_RECORD_NOT_FOUND.getCode(),RespCodeEnum.REPORT_DAILY_FILE_RECORD_NOT_FOUND.getMsg());
}
String filePath = reportDaily.getReportFile();
reportDailyService.downLoadFile(response,filePath);
}
@Override
public void downLoadFile(HttpServletResponse response, String filePath) {
File file = new File(filePath);
if(!file.exists()){
throw new BusinessException(RespCodeEnum.REPORT_DAILY_FILE_NOT_FOUND.getCode(),RespCodeEnum.REPORT_DAILY_FILE_NOT_FOUND.getMsg());
}
// 开始下载文件
InputStream in = null;
try {
// 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
// 2.设置文件头:最后一个参数是设置下载文件名
response.addHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(file.getName(), ENCODING));
in = new FileInputStream(file);
// 3.通过response获取ServletOutputStream对象(out)
int b = 0;
byte[] buffer = new byte[512];
while (b != -1) {
b = in.read(buffer);
if (b != -1) {
//4.写到输出流(out)中
response.getOutputStream().write(buffer, 0, b);
}
}
} catch (Exception e) {
log.error("download failed",e);
} finally {
try {
if (in != null) {
in.close();
}
response.getOutputStream().flush();
} catch (IOException e) {
log.error("An exception occurred when releasing the resource",e);
}
}
}
标签:文件,filePath,reportDailyDownloadReq,备忘,FILE,new,response,下载 From: https://www.cnblogs.com/falcon-fei/p/17362033.html总是有些基础内容用过就忘掉了,缺少总结记录。在此记录下来便于以后查找也为遇到类似问题的人一个小小的帮助。