Notice
Recent Posts
Recent Comments
Link
투케이2K
178. (TWOK/UTIL) [Web/JavaScript] 자바스크립트 AWS STS 사용 Long 형식 S3 파일 다운 GetPreSignedUrl 프리사인 URL 주소 생성 본문
투케이2K 유틸파일
178. (TWOK/UTIL) [Web/JavaScript] 자바스크립트 AWS STS 사용 Long 형식 S3 파일 다운 GetPreSignedUrl 프리사인 URL 주소 생성
투케이2K 2025. 12. 26. 11:07728x90
[설 명]
프로그램 : Web / JavaScript
설 명 : [Web/JavaScript] 자바스크립트 AWS STS 사용 Long 형식 S3 파일 다운 GetPreSignedUrl 프리사인 URL 주소 생성
[소스 코드]
-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------
- 개발 환경 : Web
- 개발 기술 : JavaScript (자바스크립트) / AWS / S3 / Get URL / Long / Params
- 사전) AWS S3 간략 설명 :
>> Aws S3 버킷 이란 데이터 (사진, 동영상, 문서 등) 객체 를 업로드할 수 있는 컨테이너 (디렉토리) 입니다
>> Aws S3 버킷은 온라인 스토리지 서비스로 HTTP/HTTPS 를 통한 API 를 사용해 파일 업로드 및 다운로드 처리를 할 수 있습니다
- 사전) STS 임시 보안 자격 증명 설명 정리 :
>> AWS STS 는 AWS 리소스에 대한 액세스를 제어할 수 있는 임시 보안 자격 증명입니다 (신뢰받는 사용자에게 제공)
>> AWS STS 는 단기적 임시 보안 자격 증명이며, 몇 분에서 몇 시간 동안 해당 자격 증명을 사용해 AWS 리소스를 액세스할 수 있습니다
>> AWS STS 임시 보안 자격 증명이 만료 된 경우 AWS는 더는 그 자격 증명을 인식하지 못하거나 그 자격 증명을 사용한 API 요청으로부터 이루어지는 어떤 종류의 액세스도 허용하지 않습니다
- 사전) HTTP 응답 헤더 Content-Disposition 간략 설명 (ResponseContentDisposition) :
>> Content-Disposition 는 HTTP 표준 헤더 Content-Disposition을 설정하여 파일을 브라우저에서 열지(inline) 또는 다운로드 강제(attachment)할지 지정할 수 있습니다
>> Content-Disposition 는 파일 다운로드 시 사용할 파일명을 지정할 수 있습니다
>> Content-Disposition 'inline' 옵션 : 브라우저에서 바로 열기 (PDF, 이미지 등) / Content-Disposition: inline; filename="report.pdf"
>> Content-Disposition 'attachment' 옵션 : 다운로드 강제 / Content-Disposition: attachment; filename="report.pdf"
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------
<!DOCTYPE HTML>
<html lang="ko">
<head>
<title>javaScriptTest</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 반응형 구조 만들기 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<!-- 내부 CSS 스타일 지정 -->
<style>
html, body {
width: 100%;
height: 100%;
margin : 0 auto;
padding : 0;
border : none;
background-color: #666;
}
</style>
<!-- [CDN 주소 설정] -->
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1416.0.min.js"></script>
<!-- [자바스크립트 코드 지정] -->
<script>
// --------------------------------------------------------------------------------------------------------------
// ✅ [지정 된 횟수 만큼 랜덤 문자열 만들기]
function getRandomString(length) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
// --------------------------------------------------------------------------------------------------------------
// [전역 변수 선언]
const region = 'ap-northeast-2'; // [AWS 리전]
const accessKeyId = 'AK..7Q'; // [IAM 액세스 키]
const secretAccessKey = 'Zz..xj'; // [IAM 시크릿 키]
const fileName = "20251215_CAMERA_FRM";
const bucket = 'service'; // [S3 버킷 이름]
const key = 'camera/Firmware/'+fileName; // [S3 폴더 및 파일 경로]
const expiredTime = 36000; // [STS 임시 자격 증명 및 파일 다운 로드 유효 시간 : 36000 (10시간)]
//const responseContentDisposition = 'attachment; filename="20251215_CAMERA_FRM"';
//const responseContentDisposition = 'attachment; filename="' + 'a'.repeat(500) + '.txt"';
const responseContentDisposition = 'attachment; filename="' + fileName + '-' + getRandomString(500) + '"'; // ✅ Long URL 만들기 위해 파일 다운로드 처리 옵션 지정 (inline브라우저에서 열기 (PDF, 이미지 등) / attachment : 파일 다운로드 강제)
// --------------------------------------------------------------------------------------------------------------
// [html 최초 로드 및 이벤트 상시 대기 실시]
window.onload = function() {
console.log("");
console.log("=========================================");
console.log("[window onload] : [start]");
console.log("=========================================");
console.log("");
// -----------------------------------------
// ✅ [AWS.config 지정] : 1차 IAM 계정
// -----------------------------------------
AWS.config.update({
region: region,
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey
});
// -----------------------------------------
// [AWS.STS 객체 생성]
// -----------------------------------------
const sts = new AWS.STS();
// -----------------------------------------
// [STS getSessionToken 호출 수행]
// -----------------------------------------
// DurationSeconds : Expiration 시간 3600 은 (1시간) / 세션 지속 시간 (최대 129600초 = 36시간)
// -----------------------------------------
sts.getSessionToken({ DurationSeconds: expiredTime }, function(err, data) {
if (err) {
console.error("");
console.error("=========================================");
console.error("[getSessionToken] : [Error]");
console.error("---------------------------------------");
console.error(err);
console.error("=========================================");
console.error("");
// [Body 표시 JSON]
var errJson = {
respones: "error",
data: err
}
//document.body.innerHTML = JSON.stringify(errJson); // [1 표시]
document.write(JSON.stringify(errJson)); // [2 표시]
} else {
console.log("");
console.log("=========================================");
console.log("[getSessionToken] : [Success]");
console.log("---------------------------------------");
console.log("AccessKeyId :: " + data.Credentials.AccessKeyId); // [STS > AccessKeyId]
console.log("SecretAccessKey :: " + data.Credentials.SecretAccessKey); // [STS > SecretAccessKey]
console.log("SessionToken :: " + data.Credentials.SessionToken); // [STS > SessionToken]
console.log("Expiration :: " + data.Credentials.Expiration); // [STS > Expiration]
console.log("=========================================");
console.log("");
// [void 클로저 함수 정의 실시]
let voidFunction = async function(){
console.log("");
console.log("=========================================");
console.log("[voidFunction] : [start]");
console.log("=========================================");
console.log("");
// -----------------------------------------
// ✅ [AWS.config 지정] : 2차 내려 받은 STS 임시 접근 계정
// -----------------------------------------
AWS.config.update({
region: region,
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken,
signatureVersion: "v4", // [API 요청용 AWS Signature Version 4]
});
// -----------------------------------------
// [AWS.S3 객체 생성]
// -----------------------------------------
const s3 = new AWS.S3();
// -----------------------------------------
// [GET 확인 용도 : Pre-Signed URL 생성 요청]
// -----------------------------------------
const getExpiresInSeconds = expiredTime; // 파일 다운로드 만료 시간
const getParams = {
Bucket: bucket, // [버킷 이름]
Key: key, // [폴더 및 파일 경로]
Expires: getExpiresInSeconds, // [URL 유효 시간 (초)]
ResponseContentDisposition: responseContentDisposition // ✅ 응답 오버라이드로 길이 증가 설정 (파일 다운로드 명칭 지정)
};
const getUrl = await s3.getSignedUrl('getObject', getParams);
console.log("");
console.log("=========================================");
console.log("[Get - PreSignedUrl] : [Success]");
console.log("---------------------------------------");
console.log("url :: " + getUrl);
console.log("=========================================");
console.log("");
// -----------------------------------------
// [Body 표시 JSON]
// -----------------------------------------
var resJson = {
respones: "success",
data: {
getPreSignedUrl: getUrl
}
}
//document.body.innerHTML = JSON.stringify(resJson); // [1 표시]
document.write(JSON.stringify(resJson)); // [2 표시]
};
voidFunction(); // [클로저 함수 호출]
}
});
};
// --------------------------------------------------------------------------------------------------------------
</script>
</head>
<body>
</body>
</html>
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------
[자바스크립트 AWS STS 임시 자격 증명 사용 및 Long 형식 S3 파일 다운로드 GetPreSignedUrl 프리 사인 URL 주소 생성]
https://kkh0977.tistory.com/8506
https://blog.naver.com/kkh0977/224113302155
[자바스크립트 AWS STS 임시 자격 증명 사용해 S3 Get PreSignedUrl 프리 사인 URL 주소 생성]
https://kkh0977.tistory.com/8151
https://blog.naver.com/kkh0977/223938740405
[Aws S3 Storage] S3 (Amazon Simple Storage Service) 버킷 저장소 개념 및 설명 정리
https://blog.naver.com/kkh0977/223733087281?trackingCode=blog_bloghome_searchlist
-----------------------------------------------------------------------------------------
728x90
반응형
'투케이2K 유틸파일' 카테고리의 다른 글
Comments
