Spring 기반에서 Server File 을 받아야 하는 경우.
간단하게 구현할 수 있음.
@GetMapping("/downloadFile/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request){
// Load file as Resource
Resource resource = null;
Path filePath = Paths.get("/data/log/cds",fileName);
String path = request.getHeader("file-path");
if(path!=null) {
filePath = Paths.get(path,fileName);
}
System.out.println("Begin to Download file...");
try {
resource = new UrlResource(filePath.toUri());
if(!resource.exists()) {
throw new SecurityException(HttpStatus.INTERNAL_SERVER_ERROR, filePath + " 파일을 찾을 수 없습니다.");
}
}catch(MalformedURLException e) {
throw new SecurityException(HttpStatus.INTERNAL_SERVER_ERROR, filePath + " 파일을 찾을 수 없습니다.");
}
System.out.println("Download file is : " +resource.toString());
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
logger.info("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if(contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
위와 같이 구현 하면, Rest URL 을 통하거나, parameter를 받아서 Download를 할수 있음.
굿~