기존의 S3에 업로드된 파일을 다운로드 할것이다.
그렇게 하기 위해선 일단 다운로드 버튼에서 파일의 기본적인 값을 넘겨줘야함
const imgDownloadForm = (btn) => {
// data-* 속성에서 값 추출 (경로, 이름)
const objectKey = btn.getAttribute('data-key');
const fileName = btn.getAttribute('data-filename');
console.log(objectKey);
// Presigned URL을 받아오는 Ajax 요청
fetch('/successcase/download?objectKey=' + encodeURIComponent(objectKey) + '&fileName=' + encodeURIComponent(fileName))
.then(response => {
if (!response.ok) throw new Error('Presigned URL 요청 실패');
return response.text(); // Presigned URL이 문자열로 리턴됨
})
.then(presignedUrl => {
window.open(presignedUrl, '_blank'); // 새창에서 다운로드 진행
})
.catch(err => {
alert('다운로드 중 오류가 발생했습니다: ' + err.message);
});
};
그리고 나서 아마존 S3를 관리하는 유틸 클래스에 다운로드 함수 추가
public static String generateDownloadUrl(String bucketName, String objectKey, String region, String accessKey, String secretKey, String fileName) {
// 1. S3 클라이언트 생성
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
.build();
// 2. 만료 시간 설정 (예: 1분)
Date expiration = new Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += 1000 * 60; // 1분
expiration.setTime(expTimeMillis);
// 3. Presigned URL 생성 요청 객체 생성
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.GET)
.withExpiration(expiration);
// 4. 반드시 다운로드 헤더 추가!
generatePresignedUrlRequest.addRequestParameter(
"response-content-disposition", "attachment; filename=\"" + fileName + "\""
);
// 5. Presigned URL 생성
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
return url.toString();
}
generateDownloadUrl 메서드입니다. 이 URL은 AWS 자격 증명 없이도 특정 시간 동안 파일에 접근할 수 있도록 허용합니다.bucketName (String): 파일이 저장된 S3 버킷의 이름입니다.objectKey (String): S3 버킷 내에서 파일의 경로와 이름 (예: documents/report.pdf).region (String): S3 버킷이 위치한 AWS 리전 (예: ap-northeast-2 for 서울).accessKey (String): AWS 계정의 접근 키입니다. (보안상 민감한 정보이므로 주의하여 관리해야 합니다.)secretKey (String): AWS 계정의 비밀 키입니다. (보안상 민감한 정보이므로 주의하여 관리해야 합니다.)fileName (String): 사용자가 파일을 다운로드할 때 표시될 파일 이름입니다.AmazonS3 s3Client)AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
.build();
AmazonS3ClientBuilder.standard(): S3 클라이언트 빌더의 표준 인스턴스를 가져옵니다..withRegion(region): 클라이언트가 통신할 AWS 리전을 설정합니다. 이는 S3 버킷이 위치한 리전과 일치해야 합니다..withCredentials(...): S3에 접근하기 위한 AWS 자격 증명(Access Key와 Secret Key)을 제공합니다. AWSStaticCredentialsProvider는 제공된 자격 증명을 사용하여 클라이언트를 인증합니다..build(): 설정된 정보를 바탕으로 AmazonS3 클라이언트 객체를 최종적으로 생성합니다.expiration)Date expiration = new Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += 1000 * 60; // 1분
expiration.setTime(expTimeMillis);