需求:
SpringBoot项目中,需要下载一些文件资源,例如Excel表格。
一、思路:
1.准备好文件放在特定的地方(Linux或Windows);
2.通过路径获取文件;
3.读取文件,使用response中的输出流将文件以流的方式返回到前端。
二、代码的实现:
controller层:
/**
* 下载导出制网补充信息模板
*
* @param response
* @return
*/
@PostMapping("downloadTemplate")
@ApiOperation(value = "下载", httpMethod = "POST", produces = "application/json")
public void downloadInfoTemplate(HttpServletResponse response) {
infoService.downTemplateInfo(response);
}
service层:
/**
* 下载模板
*
* @param response
* @return
*/
@Value(value = "${SupplyFilePath}")
private String FILEPATH;
@Override
public void downTemplateInfo(HttpServletResponse response) {
try {
downloadFile(FILEPATH, response);
} catch (Exception e) {
log.error("文件下载出错:" + e.getMessage() + " 原路径:" + FILEPATH);
e.printStackTrace();
}
}
public void downloadFile(String filePath, HttpServletResponse response) throws Exception{
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException("找不到文件");
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset();
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("utf-8");
logger.info("filename={}",filePath);
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(f.getName(), "utf-8"));
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
IOUtils.closeQuietly(br);
IOUtils.closeQuietly(out);
}
yml文件进行路径的配置
SupplyFilePath: /home/importFile/下载.xlsx
SpringBoot实现文件上传见
https://blog.csdn.net/m0_52850461/article/details/121504536
三、注意事项:
1.用swagger测试的时候,下载的文件打开是报错:文件格式或文件一损坏,要在controller的方法上添加produces = “application/json”。
@ApiOperation(value = "下载", httpMethod = "POST", produces = "application/json")
2.在swagger和postman测试会出现文件名乱码,但是运行代码,在浏览器运行就会正常。
3.关于Windows和Linux的路径问题易错,见
https://blog.csdn.net/m0_52850461/article/details/121528554