下载文件的service实现
public ResponseEntity export(String s,String pathName) {
if (s == null) {
return null;
}
FileSystemResource fileSystemResource = new FileSystemResource(s);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition","attachment;filename="+pathName);
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
try {
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + pathName).contentLength(fileSystemResource.contentLength())
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(new InputStreamResource(fileSystemResource.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
接口(在调用service层之前调用了生成xlsx文件的代码,大佬们可以略过那里)
public ResponseEntity exportExcel(String pathName){
List<Casereportform> list = null;
try{
list = caseReportFormService.findCaseFormAll();
System.out.println(list);
}catch (Exception e){
e.printStackTrace();
}
try {
XSSFWorkbook xssfWorkbook = exportService.exportExcel(list);
String uuidFileName= UUID.randomUUID().toString().replace("-","");
uuidFileName = uuidFileName + ".xlsx";
FileOutputStream fileOutputStream = new FileOutputStream(uuidFileName);
//将文件写到服务器中
xssfWorkbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
xssfWorkbook.close();
File file = new File(uuidFileName);
//获取服务器的中的文件
ResponseEntity responseEntity = exportService.export(uuidFileName,pathName);
// 路径为文件且不为空则进行删除,将服务器的文件删除以免占用过多资源
if (file.isFile() && file.exists()) {
file.delete();
}
//将responseEntity作为返回值返回
return responseEntity;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
测试结果:
它返回一堆乱码,但是却没有下载文件,各位大佬帮忙看看呗。