@GetMapping("/file/downloadURL")
public ResponseEntity<?> downloadURL(@RequestParam String fileId, HttpServletRequest request) throws MalformedURLException {
// fileId를 통해 파일 정보 조회
FileManageVO fileManageVO = fileManageService.selectFile(fileId);
String orgnFileNm = fileManageVO.getOrgnFileNm(); // 원본 파일 이름
String strgFileNm = fileManageVO.getStrgFileNm(); // 저장된 파일 이름
String strgFilePth = fileManageVO.getStrgFilePath(); // 저장된 파일 경로
String fileExtn = fileManageVO.getFileExt(); // 파일 확장자
String encodedFileNm = UriUtils.encode(orgnFileNm, StandardCharsets.UTF_8); // URL 인코딩된 파일 이름
String disposition = "attachment; filename=\"" + encodedFileNm + ((fileExtn != null) ? "." + fileExtn : "") + "\""; // 다운로드 헤더 설정
UrlResource resource = new UrlResource("file:" + uploadPath + File.separator + strgFilePth + File.separator + strgFileNm); // 다운로드할 파일의 URL 리소스 생성
// 첫 다운로드 시간 저장 (파일 다운로드 시간 기준으로 유효 기간을 설정)
String downloadStartTime = (String) request.getSession().getAttribute(fileId + "_downloadStartTime");
if (downloadStartTime == null) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
downloadStartTime = now.format(formatter); // 현재 시간을 포맷에 맞게 문자열로 저장
request.getSession().setAttribute(fileId + "_downloadStartTime", downloadStartTime); // 세션에 다운로드 시작 시간 저장
}
// 현재 시간과 다운로드 시작 시간을 비교하여 유효 기간 검사
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime downloadStartDateTime = LocalDateTime.parse(downloadStartTime, formatter); // 문자열로부터 LocalDateTime 객체로 변환
Duration duration = Duration.between(downloadStartDateTime, now); // 다운로드 시간과 현재 시간의 간격을 계산하여 Duration 객체로 반환
// 유효 기간이 30분 이내인지 검사
if (duration.toMinutes() > 30) {
// 유효 기간이 지났으므로 URL을 만료시키고 적절한 응답을 반환
request.getSession().removeAttribute(fileId + "_downloadStartTime"); // 세션에서 다운로드 시작 시간 제거
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("URL의 유효 기간이 만료되었습니다."); // 403 Forbidden 응답 반환
}
// 파일 다운로드 응답 반환
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, disposition).body(resource);
}
'개발자 > Spring' 카테고리의 다른 글
서버 재시작 없이 HTML 변경사항 실시간 반영하기: Spring Boot 개발자를 위한 가이드 (0) | 2024.02.19 |
---|---|
[SPRING] Interceptor의 의미와 구현 및 실습 (0) | 2023.01.10 |
[SPRING] 다중 파일 업로드(중첩 커맨드객체) (0) | 2023.01.04 |
[SPRING] spring으로 파일 업로드 구현 (0) | 2023.01.03 |
[SPRING] 간단하게 홈 컨트롤러 대체하기(GET,POST 방식으로 구분하지 않을때) (0) | 2023.01.03 |