개발../Javascript
자바스크립트를 이용해 base64 를 엑셀로 다운로드 기능 구현
링재호
2023. 9. 15. 15:12
보통 서비스 / 데이터 가공 구간에서 저장하고 있는 파일을 base64로 파싱하여 프론트로 내려주게 된다.
그리고 이를 이용해 프론트는 base64 를 디코딩하여 blob 객체를 생성하고 이를 이용해 파일을 다운로드한다.
여기서 궁금한 점은 base64 로 왜 인코딩해서 내려주냐? 인데, 간단하게 바이너리 데이터를 텍스트 데이터로 변경해서 내려주기 때문에 성능, 보완에 장점이 있다고 한다. 예를 들어, JSON 을 텍스트로 변경해서 내려주는거를 상상하면 이해가 될 것이다.
코드
아래는 base 64 데이터를 받아왔다는 가정하에 아래에 base64 로 데이터를 넣으면 xlsx 를 다운받을 수 있을 것이다.
/**
* base64 를 받아 엑셀 다운로드 하는 함수
* @param {base64} base64Data base64 데이터
* @param {string} fileName 파일 이름 (기본값: test)
* @param {string} fileType 파일 타입 (기본값: xlsx)
*/
const fileDownload = (base64Data, fileName = "test", fileType = "xlsx") => {
if (!base64Data) return;
// Base64 디코딩
const decodedData = atob(base64Data);
// Uint8Array로 변환
const dataArray = new Uint8Array(decodedData.length);
for (let i = 0; i < decodedData.length; i++) {
dataArray[i] = decodedData.charCodeAt(i);
}
// MIME 유형 결정
let type = "";
switch (fileType) {
case "xlsx":
type =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
case "docx":
type =
"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
break;
case "txt":
type = "text/plain";
break;
case "csv":
type = "text/csv";
break;
// 추가적인 파일 유형을 여기에 추가할 수 있습니다.
default:
type = "application/octet-stream"; // 기본 이진 파일 유형
}
// Blob 생성
const blob = new Blob([dataArray], {
type,
});
// Blob URL 생성
const blobURL = URL.createObjectURL(blob);
// 다운로드 링크 생성
const downloadLink = document.createElement("a");
downloadLink.href = blobURL;
downloadLink.download = `${fileName}.${fileType}`; // 파일 이름
// 다운로드 링크 클릭
downloadLink.click();
// Blob URL 해제
URL.revokeObjectURL(blobURL);
};