Merge branch 'susu' into dev
This commit is contained in:
@@ -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("파일 다운로드에 실패하였습니다.");
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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);*/
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -29,6 +30,11 @@ class GetNoticeDao implements GetNoticePortOut {
|
||||
@Transactional
|
||||
public Optional<GetNotice> operate(GetNoticeCmd command) {
|
||||
GetNotice secArticle = mapper.getNotice(command);
|
||||
if (secArticle.getContent() != null) {
|
||||
String cleanedContent = HtmlUtils.htmlUnescape(secArticle.getContent());
|
||||
cleanedContent = cleanedContent.replaceAll("<p>\\s*</p>", "</br>");
|
||||
secArticle.setContent(cleanedContent);
|
||||
}
|
||||
|
||||
List<GetNoticeUploadFile> setArticleUploadFile =
|
||||
mapper.getUploadFiles(command.getId());
|
||||
|
||||
@@ -39,8 +39,7 @@
|
||||
resultType="app.module.front.usecase.info.notice.getNotice.ports.application.domain.GetNoticeUploadFile">
|
||||
/* getUploadFiles 상세 게시글 조회 시, 첨부파일 조회 */
|
||||
SELECT
|
||||
awuf.notice_id AS noticeId,
|
||||
awuf.upload_files_id AS uploadfileId,
|
||||
uf.mapping_id AS noticeId,
|
||||
uf.id AS id,
|
||||
uf.created_at AS createdAt,
|
||||
uf.created_by AS createdBy,
|
||||
@@ -51,9 +50,7 @@
|
||||
uf.origin_name AS originName,
|
||||
uf.path AS path,
|
||||
uf.type AS type
|
||||
FROM notice_has_upload_file awuf
|
||||
INNER JOIN upload_file uf
|
||||
ON awuf.upload_files_id = uf.id
|
||||
WHERE awuf.notice_id = #{id}
|
||||
FROM upload_file uf
|
||||
WHERE uf.mapping_id = #{id} and uf.is_deleted = false and uf.type='NOTICE'
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -13,15 +13,21 @@
|
||||
</dd>
|
||||
</dl>
|
||||
<div class="detail-content">
|
||||
<p th:utext="${notice.content}"></p>
|
||||
<p th:utext="${ notice.content }"></p>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="download-file" th:if="${!#lists.isEmpty(notice.uploadFiles)}">
|
||||
<p class="tit">첨부파일</p>
|
||||
<ul>
|
||||
<li th:each="item : ${notice.uploadFiles}"><a th:href="${item.attachmentURL}" download
|
||||
th:text="${item.originName}"></a></li>
|
||||
<li th:each="item : ${notice.uploadFiles}">
|
||||
<a href="javascript:void(0);"
|
||||
th:text="${item.originName}"
|
||||
th:data-url="${item.attachmentURL}"
|
||||
th:data-filename="${item.originName}"
|
||||
onclick="formControl.fileDownload(this)">
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -57,13 +63,71 @@ root: /*[[|#{uri.front.info.user.path}/password|]]*/'rootUrl',
|
||||
*/
|
||||
const previousUrl = document.referrer;
|
||||
|
||||
if (previousUrl.includes('/info/notice')) {
|
||||
/* if (previousUrl.includes('/info/notice')) {
|
||||
history.back();
|
||||
} else {
|
||||
} 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);
|
||||
});
|
||||
|
||||
}
|
||||
},
|
||||
|
||||
}
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user