Notice
Recent Posts
Recent Comments
Link
투케이2K
473. (javaScript) 자바스크립트 파일 다운로드 Get URL 주소에서 커스텀 파라미터 추가해 Long Url 생성 및 a 태그 파일 다운로드 수행 본문
JavaScript
473. (javaScript) 자바스크립트 파일 다운로드 Get URL 주소에서 커스텀 파라미터 추가해 Long Url 생성 및 a 태그 파일 다운로드 수행
투케이2K 2025. 12. 19. 13:30728x90
[개발 환경 설정]
개발 툴 : Edit++
개발 언어 : JavaScript
[소스 코드]
-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------
- 개발 환경 : Web
- 개발 기술 : JavaScript (자바스크립트) / AWS / S3 / File Download Url
- 사전) AWS S3 간략 설명 :
>> Aws S3 버킷 이란 데이터 (사진, 동영상, 문서 등) 객체 를 업로드할 수 있는 컨테이너 (디렉토리) 입니다
>> Aws S3 버킷은 온라인 스토리지 서비스로 HTTP/HTTPS 를 통한 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>
// --------------------------------------------------------------------------------------------------------------
// ✅ [지정 된 횟수 만큼 랜덤 문자열 만들기]
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 DEFAULT_FILE_DOWN_URL = 'https://service.s3.ap-northeast-2.amazonaws.com/menu/twok.pdf'; // [AWS S3 퍼블릭 접근 및 파일 다운로드 가능 주소]
//const DEFAULT_FILE_DOWN_URL = 'https://service.s3.ap-northeast-2.amazonaws.com/menu/Firmware/20251215_CAMERA'; // [AWS S3 퍼블릭 접근 및 파일 다운로드 가능 주소]
const ADD_LOG_PARAMS = '?addCustomLongUrlParams=' + getRandomString(500); // ✅ Long URL 만들기 위해 기본 주소에 커스텀 파라미터 추가
// --------------------------------------------------------------------------------------------------------------
// [html 최초 로드 및 이벤트 상시 대기 실시]
window.onload = async function() {
console.log("");
console.log("=========================================");
console.log("[window onload] : [start]");
console.log("----------------------------------------");
console.log("[DEFAULT_FILE_DOWN_URL] : ", DEFAULT_FILE_DOWN_URL);
console.log("----------------------------------------");
console.log("[ADD_LOG_PARAMS] : ", ADD_LOG_PARAMS);
console.log("=========================================");
console.log("");
// -----------------------------------------
// [HTTP 파일 다운로드 URL 생성]
// -----------------------------------------
const FILE_URL = DEFAULT_FILE_DOWN_URL + ADD_LOG_PARAMS;
console.log("");
console.log("=========================================");
console.log("[window onload] : [FILE_URL]");
console.log("----------------------------------------");
console.log(FILE_URL);
console.log("=========================================");
console.log("");
// -----------------------------------------
// ✅ [커스텀 생성한 URL 을 Get 호출로 파일이 다운로드 되는지 확인 수행]
// -----------------------------------------
const res = await fetch(FILE_URL, { method: 'GET' });
if (!res.ok) {
console.error("");
console.error("=========================================");
console.error("[window onload] : [fetch] : Error");
console.error("----------------------------------------");
console.error("status : ", res.status);
console.error("----------------------------------------");
console.error("statusText : ", res.statusText);
console.error("=========================================");
console.error("");
}
else {
console.log("");
console.log("=========================================");
console.log("[window onload] : [fetch] : Result");
console.log("----------------------------------------");
console.log("status : ", res.status);
console.log("----------------------------------------");
console.log("statusText : ", res.statusText);
console.log("=========================================");
console.log("");
// 응답을 Blob 으로 변환 (파일 객체)
const blob = await res.blob();
// 브라우저에서 파일 다운로드를 위한 a 태그 생성
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = objectUrl;
// 서버가 Content-Disposition 헤더로 파일명을 내려주는 경우 파싱
/*
const cd = res.headers.get('Content-Disposition');
const filename = cd && cd.includes('filename=') ? (
// filename="..." 형태 추출
cd.match(/filename\*=UTF-8''([^;]+)|filename="([^"]+)"/)?.[1] || cd.match(/filename="([^"]+)"/)?.[1]
) : 'download.bin';
// */
// ✅ 생성한 a 태그 동적 body 에 추가 및 클릭 이벤트 발생으로 파일 다운로드 수행
a.download = decodeURIComponent("work_private.txt"); // 다운로드 되는 파일 명칭 지정
document.body.appendChild(a);
a.click(); // 파일 다운로드 수행
a.remove(); // 태그 다시 제거
URL.revokeObjectURL(objectUrl);
}
};
// --------------------------------------------------------------------------------------------------------------
</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
반응형
'JavaScript' 카테고리의 다른 글
Comments
