需求:获取reouurces目录下的文件:重点植物导入模版
?获取到文件:
public static void main(String[] args) {
// 获取 resource 目录下的所有文件
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resourcePatternResolver.getResources("classpath*:/**/*.xml");
for (Resource resource : resources) {
System.out.println(resource.getURL());
}
}
?获取文件并下载:
/**
* 下载导出模板
*/
@GetMapping("/downloadFile")
@ApiOperationSupport(order = 12)
@ApiOperation(value = "下载", notes = "下载")
public ResponseEntity<Resource> downloadFile() throws IOException {
String encodedFileName = CommonUtil.encodeFileName(CommonConstant.BACKGROUND_RESOURCES_EXCEL);
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resourcePatternResolver.getResources("classpath*:/**/*.xlsx");
Resource file = null;
for (Resource resource : resources) {
String url = resource.getURL().getPath();
if (url.contains(CommonConstant.BACKGROUND_RESOURCES_EXCEL)) {
file = resource;
}
}
// 构建ResponseEntity对象
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"");
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
return ResponseEntity.ok()
.headers(headers)
.body(file);
}
?