From fe9a0a059e50520454ecde252d656e1fbce93fec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A3=BC=EC=88=98=ED=98=84?= Date: Tue, 15 Jul 2025 15:30:10 +0900 Subject: [PATCH] =?UTF-8?q?=EA=B3=B5=EC=A7=80=EC=82=AC=ED=95=AD=20?= =?UTF-8?q?=EC=B2=A8=EB=B6=80=20=ED=8C=8C=EC=9D=BC=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../adapters/DownloadFileController.java | 2 +- .../adapters/persistence/UpdateFileDao.java | 4 +- .../url/strategy/SftpFileUrlStrategy.java | 2 +- .../adapters/web/GetAttachmentController.java | 99 +++++++++++++++---- .../resources/templates/info/notice/{id}.html | 70 ++++++++++++- 5 files changed, 149 insertions(+), 28 deletions(-) diff --git a/core/src/main/java/app/module/core/usecase/file/downloadFile/adapters/DownloadFileController.java b/core/src/main/java/app/module/core/usecase/file/downloadFile/adapters/DownloadFileController.java index 68cb3270..d9a8f718 100644 --- a/core/src/main/java/app/module/core/usecase/file/downloadFile/adapters/DownloadFileController.java +++ b/core/src/main/java/app/module/core/usecase/file/downloadFile/adapters/DownloadFileController.java @@ -38,7 +38,7 @@ class DownloadFileController { // 로컬 파일 경로 File downloadedFile = new File(file.getLocalPath()); if (!downloadedFile.exists()) { - throw new IllegalStateException("Downloaded file not found: " + file.getLocalPath()); + throw new IllegalStateException("파일 다운로드에 실패하였습니다."); } diff --git a/core/src/main/java/app/module/core/usecase/file/updateFile/adapters/persistence/UpdateFileDao.java b/core/src/main/java/app/module/core/usecase/file/updateFile/adapters/persistence/UpdateFileDao.java index 4465e0b4..bf43ea60 100644 --- a/core/src/main/java/app/module/core/usecase/file/updateFile/adapters/persistence/UpdateFileDao.java +++ b/core/src/main/java/app/module/core/usecase/file/updateFile/adapters/persistence/UpdateFileDao.java @@ -41,7 +41,7 @@ class UpdateFileDao implements UpdateFilePortOut { command.getType().getName() ))); - for (UploadFileDto file : deletedFileList) { +/* for (UploadFileDto file : deletedFileList) { try { sftpFileDeleteUtil.deleteRealFile(file); } catch (JSchException | SftpException e) { @@ -51,7 +51,7 @@ class UpdateFileDao implements UpdateFilePortOut { log.error("Unexpected error while deleting file for mapping ID {}: {}", file.getId(), e.getMessage(), e); throw new RuntimeException("Unexpected error while deleting file", e); } - } + }*/ if (!deletedFileList.isEmpty()) { mapper.deleteFile( diff --git a/core/src/main/java/app/module/core/usecase/file/url/strategy/SftpFileUrlStrategy.java b/core/src/main/java/app/module/core/usecase/file/url/strategy/SftpFileUrlStrategy.java index adde9d46..34f25031 100644 --- a/core/src/main/java/app/module/core/usecase/file/url/strategy/SftpFileUrlStrategy.java +++ b/core/src/main/java/app/module/core/usecase/file/url/strategy/SftpFileUrlStrategy.java @@ -18,7 +18,7 @@ public class SftpFileUrlStrategy implements FileUrlStrategy { @Override public String getAttachmentURL(Long fileId) { - return String.format("/api/file/download/%s", fileId); + return String.format("/content-disposition/attachment/%s", fileId); } } diff --git a/core/src/main/java/app/module/core/usecase/getAttachment/adapters/web/GetAttachmentController.java b/core/src/main/java/app/module/core/usecase/getAttachment/adapters/web/GetAttachmentController.java index 8a27bab1..ef498537 100644 --- a/core/src/main/java/app/module/core/usecase/getAttachment/adapters/web/GetAttachmentController.java +++ b/core/src/main/java/app/module/core/usecase/getAttachment/adapters/web/GetAttachmentController.java @@ -1,27 +1,42 @@ package app.module.core.usecase.getAttachment.adapters.web; import app.module.core.config.application.enums.FileStorageType; +import app.module.core.config.application.util.SftpFileDownloader; import app.module.core.usecase.file.getFile.ports.GetFilePortIn; import app.module.core.usecase.file.getFile.ports.application.domain.GetFile; import app.module.core.usecase.file.getFile.ports.application.domain.GetFileCmd; + +import java.io.File; +import java.io.IOException; import java.net.MalformedURLException; +import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; + +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.SftpException; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriUtils; +@Slf4j @RestController @RequiredArgsConstructor class GetAttachmentController { private final GetFilePortIn getFilePortIn; + private final SftpFileDownloader sftpFileDownloader; + @Value("${path.upload.public}") private String publicPath; @Value("${app.aws.s3.domain:null}") @@ -34,11 +49,14 @@ class GetAttachmentController { @GetMapping(path = "/content-disposition/attachment/{fileId}") ResponseEntity operate(@PathVariable Long fileId) throws MalformedURLException { - GetFile getFile = - getFilePortIn - .operate(new GetFileCmd(fileId)) - .orElseThrow( - () -> new RuntimeException(String.format("파일을 찾을 수 없습니다. ID: %s", fileId))); + GetFile getFile; + try { + getFile = getFilePortIn.operate(new GetFileCmd(fileId)) + .orElseThrow(() -> new RuntimeException(String.format("파일을 찾을 수 없습니다. ID: %s", fileId))); + } catch (RuntimeException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body("파일을 찾을 수 없습니다: " + e.getMessage()); + } // TODO - private 업로드 기능을 일단 mute @@ -56,35 +74,74 @@ class GetAttachmentController { // () -> new AccessDeniedException("[AccessDenied] Private 파일 리소스 접근 권한이 없습니다.")); // } + // HTTP 헤더 설정 + String encodedFileName = URLEncoder.encode(getFile.getOriginName(), StandardCharsets.UTF_8) + .replace("+", "%20"); + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName); + headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); + headers.add(HttpHeaders.PRAGMA, "no-cache"); + headers.add(HttpHeaders.EXPIRES, "0"); + UrlResource resource = null; switch (FileStorageType.valueOf(uploadStorageType)) { case LOCAL: - String filePath = - Paths.get(publicPath, getFile.getPath(), getFile.getName()) - .toString(); + String filePath = Paths.get(publicPath, getFile.getPath(), getFile.getName()).toString(); + File localFile = new File(filePath); + if (!localFile.exists()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body("파일을 찾을 수 없습니다: "); + } + return ResponseEntity.ok() + .headers(headers) + .contentLength(localFile.length()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .body(new FileSystemResource(localFile)); - resource = new UrlResource("file:" + filePath); - break; case S3: - resource = - new UrlResource( - "https://" - + cloudFrontDomain - + bucketFolder - + getFile.getPath() - + "/" - + getFile.getName()); - break; + String s3Url = "https://" + cloudFrontDomain + bucketFolder + getFile.getPath() + "/" + getFile.getName(); + UrlResource s3Resource = new UrlResource(s3Url); + if (!s3Resource.exists()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body("S3 파일을 찾을 수 없습니다: " + s3Url); + } + return ResponseEntity.ok() + .headers(headers) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .body(s3Resource); + + case SFTP: + try { + sftpFileDownloader.downloadFile(getFile); + } catch (JSchException | SftpException | IOException e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("SFTP 파일 다운로드에 실패했습니다: " + e.getMessage()); + } + File downloadedFile = new File(getFile.getLocalPath()); + if (!downloadedFile.exists()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body("다운로드된 파일을 찾을 수 없습니다: " + getFile.getLocalPath()); + } + + return ResponseEntity.ok() + .headers(headers) + .contentLength(downloadedFile.length()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .body(new FileSystemResource(downloadedFile)); + + default: + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body("지원되지 않는 저장소 타입입니다: " + uploadStorageType); } - String encodedUploadFileName = UriUtils.encode(getFile.getOriginName(), + /* String encodedUploadFileName = UriUtils.encode(getFile.getOriginName(), StandardCharsets.UTF_8); String contentDisposition = "attachment; filename=\"" + encodedUploadFileName + "\""; return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) - .body(resource); + .body(resource);*/ } } diff --git a/front/src/main/resources/templates/info/notice/{id}.html b/front/src/main/resources/templates/info/notice/{id}.html index 8d09afee..791241cd 100644 --- a/front/src/main/resources/templates/info/notice/{id}.html +++ b/front/src/main/resources/templates/info/notice/{id}.html @@ -20,8 +20,14 @@

첨부파일

@@ -62,8 +68,66 @@ root: /*[[|#{uri.front.info.user.path}/password|]]*/'rootUrl', } else { location.href = '/info/notice'; } + }, + fileDownload(element) { + const url = element.dataset.url; + const fileName = element.dataset.filename; + if (!url || !fileName) { + console.error('Invalid URL or fileName:', url, fileName); + ajaxUtil._alert('파일 다운로드를 시작할 수 없습니다: 유효하지 않은 URL 또는 파일명입니다.', null); + return; + } + fetch(url, { + method: 'GET', + headers: { + 'Accept': 'application/octet-stream' + } + }).then(response => { + console.log('Response status:', response.status); + if (!response.ok) { + // 응답 본문 읽기 + return response.text().then(errorMessage => { + let message = errorMessage || '파일 다운로드에 실패했습니다. 상태 코드: ' + response.status; + if (response.status === 404) { + message = errorMessage || '파일을 찾을 수 없습니다.'; + } else if (response.status === 500) { + message = errorMessage || '서버 오류로 인해 파일 다운로드에 실패했습니다.'; + } + throw new Error(message); + }); + } + // Content-Disposition 헤더에서 파일명 추출 + const disposition = response.headers.get('Content-Disposition'); + console.log('Content-Disposition:', disposition); + let serverFileName = fileName; + if (disposition && disposition.includes('filename*=')) { + const matches = disposition.match(/filename\*=UTF-8''(.+)/); + if (matches && matches[1]) { + try { + serverFileName = decodeURIComponent(matches[1]); + } catch (e) { + console.error('Failed to decode filename:', e); + } + } + } + return response.blob().then(blob => ({ blob, fileName: serverFileName })); + }) + .then(({ blob, fileName }) => { + console.log('Blob received, size:', blob.size); + const link = document.createElement('a'); + link.href = window.URL.createObjectURL(blob); + link.download = fileName; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + window.URL.revokeObjectURL(link.href); + }) + .catch(error => { + console.error('Download error:', error); + ajaxUtil._alert('파일 다운로드에 실패했습니다: ', null); + }); - } + }, }