투케이2K

189. (TWOK/UTIL) [Web/JavaScript] 자바스크립트 AWS S3 GetPreSignedUrl 프리사인 URL 생성 시 inline 브라우저 표시 설정 방법 본문

투케이2K 유틸파일

189. (TWOK/UTIL) [Web/JavaScript] 자바스크립트 AWS S3 GetPreSignedUrl 프리사인 URL 생성 시 inline 브라우저 표시 설정 방법

투케이2K 2026. 5. 20. 21:33
728x90
반응형

[설 명]

프로그램 : Web / JavaScript

설 명 : [Web/JavaScript] 자바스크립트 AWS S3 GetPreSignedUrl 프리사인 URL 생성 시 inline 브라우저 표시 설정 방법

 

[소스 코드]

-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------

- 개발 환경 : Web


- 개발 기술 : Web / JavaScript / AWS / S3 / GetPreSignedUrl


- 사전) 👉 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>


        // [전역 변수 선언]
        const region = 'ap-northeast-2'; // [AWS 리전]
        const accessKeyId = 'AK..7Q'; // [IAM 액세스 키]
        const secretAccessKey = 'Zz..xj'; // [IAM 시크릿 키]

        const fileName = "20251215_TEST.pdf"; // [파일 명칭]
        
        const bucket = 'service'; // 👉 [S3 버킷 이름]
        const key = 'menu/pdfFile/'+fileName; // 👉 [S3 폴더 및 파일 경로]
        const expiredTime = 36000; // [STS 임시 자격 증명 및 파일 다운 로드 유효 시간 : 36000 (10시간)]

        // --------------------------------------------------------------------------------------------------------------

        // [html 최초 로드 및 이벤트 상시 대기 실시]
        window.onload = function() {
            console.log("[window onload] : [start]");


            // -----------------------------------------
            // ✅ [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("❌ [getSessionToken] : [Error] : ", err);

                // [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("✅ [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("=========================================");                


                // [void 클로저 함수 정의 실시]
                let voidFunction = async function(){
                    console.log("[voidFunction] : [start]");

                    // -----------------------------------------
                    // ✅ [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; // 파일 다운로드 만료 시간
                    var getParams = {
                      Bucket: bucket, // [버킷 이름]
                      Key: key, // [폴더 및 파일 경로]
                      Expires: getExpiresInSeconds // [URL 유효 시간 (초)]                      
                    }; 

                    // -----------------------------------------
                    // ✅ 특정 파일 확장자 체크 후 inline 브라우저 표시 설정 수행
                    // -----------------------------------------
                    if (key.endsWith(".yaml")){            
                        getParams.ResponseContentDisposition = 'inline';
                        getParams.ResponseContentType = 'text/yaml; charset=utf-8';   // ✅ 같이 쓰는게 중요

                        console.warn('[yaml] S3 프리사인 URL 주소 생성 특정 파일 확장자 포함 확인 : ', JSON.stringify(getParams));
                    }

                    if (key.endsWith(".pdf")){            
                        getParams.ResponseContentDisposition = 'inline';
                        getParams.ResponseContentType = 'application/pdf';   // ✅ 같이 쓰는게 중요

                        console.warn('[pdf] S3 프리사인 URL 주소 생성 특정 파일 확장자 포함 확인 : ', JSON.stringify(getParams));
                    }

                    if (key.endsWith(".txt")){
                        getParams.ResponseContentDisposition = 'inline';
                        getParams.ResponseContentType = 'text/plain; charset=utf-8';   // ✅ 같이 쓰는게 중요

                        console.warn('[txt] S3 프리사인 URL 주소 생성 특정 파일 확장자 포함 확인 : ', JSON.stringify(getParams));
                    }

                    if (key.endsWith(".zip") || key.endsWith(".7z")){
                        getParams.ResponseContentDisposition = 'attachment'; // ✅ 파일 다운로드              

                        console.warn('[zip] S3 프리사인 URL 주소 생성 특정 파일 확장자 포함 확인 : ', JSON.stringify(getParams));
                    }

                    const getUrl = await s3.getSignedUrl('getObject', getParams);

                    console.log("✅ [Get - PreSignedUrl] : [Success] : ", getUrl);


                    // -----------------------------------------
                    // [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
반응형
Comments