@GetMapping(value="/jobSeekerProfile/downloadResume", produces = "application/octet-stream")
public ResponseEntity<?> downloadResume(
@RequestParam(value = "fileName") String fileName,
@RequestParam(value = "userID") String userId) {
FileDownloadUtil downloadUtil = new FileDownloadUtil();
Resource resource = null;
try {
resource = downloadUtil.getFileAsResource("photos/candidate/" + userId, fileName); // 파일 다운로드 경로
} catch(IOException e){
return new ResponseEntity<>("File not found", HttpStatus.NOT_FOUND);
}
if(resource == null){
return new ResponseEntity<>("File not found", HttpStatus.NOT_FOUND);
}
String encodedFileName = URLEncoder.encode(resource.getFilename(), StandardCharsets.UTF_8)
.replaceAll("\\+", "%20"); // 스페이스를 대신 %20으로
String contentDisposition = "attachment; filename*=UTF-8''" + encodedFileName;
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.body(resource);
}
public class FileDownloadUtil {
private Path foundFile;
public Resource getFileAsResource(String downloadDir, String fileName) throws IOException {
Path path = Paths.get(downloadDir);
Files.list(path).forEach(file -> {
if(file.getFileName().toString().startsWith(fileName)) {
foundFile = file;
}
});
if (foundFile != null) {
return new UrlResource(foundFile.toUri());
}
return null;
}
}