37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
/**
|
|
* 📄 File Download Utility
|
|
* 파일 다운로드 유틸리티
|
|
*
|
|
* - API를 통한 파일 다운로드 처리
|
|
* - Blob 데이터를 임시 링크로 연결하여 다운로드
|
|
* - 파일명 지정 및 메모리 해제 기능
|
|
* - 에러 핸들링 및 사용자 친화적인 오류 메시지
|
|
* - 다양한 파일 타입 지원 (엑셀, PDF 등)
|
|
* - Fetch 기반 HTTP 요청 처리
|
|
*/
|
|
|
|
export const handleDownload = async (api: string, fileNm: string) => {
|
|
try {
|
|
const response = await fetch(api, {
|
|
method: 'GET',
|
|
});
|
|
if (!response.ok) throw new Error('파일 다운로드 실패');
|
|
|
|
const blob = await response.blob();
|
|
fileDownload(blob, fileNm);
|
|
} catch (error) {
|
|
console.error('다운로드 중 오류 발생:', error);
|
|
}
|
|
};
|
|
|
|
export const fileDownload = (data: Blob, fileName: string) => { // Blob데이터 임시link로 연결
|
|
const url = window.URL.createObjectURL(data);
|
|
const link = document.createElement('a');
|
|
link.href = url;
|
|
link.download = fileName; // 원하는 파일명 지정
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
// 메모리 해제
|
|
link.remove();
|
|
window.URL.revokeObjectURL(url);
|
|
} |