스프링 파일 다운로드 구현

스프링 파일 다운로드 구현


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RequestMapping(value="/{id}/download", method=RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public FileSystemResource download(@PathVariable("id") SomeObj obj, HttpServletResponse response) {
File file = myService.toFile(obj);
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
/** 보통 아래와 같이 구현했었다. 이것도 간단하긴 한데...
try {
FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
log.info("Error writing file to output stream. Filename was '" + file.getName() + "'");
throw new RuntimeException("IOError writing file to output stream");
}
*/
/* 그냥 객체 하나만 던져주면 된다. */
return new FileSystemResource(file);
}
Share