async downloadFile(url, filename) {
    if (!url) {
        this.error = true;
        console.error("파일 URL이 제공되지 않았습니다.");
        return;
    }

    this.fetching = true;
    this.error = false;

    try {
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error("네트워크 응답이 실패했습니다.");
        }

        const blob = await response.blob();

        const blobURL = URL.createObjectURL(blob);

        const a = document.createElement("a");
        a.href = blobURL;
        a.download = filename;
        a.style.display = "none";

        document.body.appendChild(a);
        a.click();
        a.remove();

        URL.revokeObjectURL(blobURL); // 메모리 누수 방지
    } catch (error) {
        console.error("파일 다운로드 중 오류 발생:", error);
        this.error = true;
    } finally {
        this.fetching = false;
    }
}

 

전체 동작 흐름

  1. URL 확인: 유효한 url이 제공되었는지 확인.
  2. 다운로드 진행 상태 설정: 다운로드가 시작되었음을 나타냄.
  3. 파일 요청: 주어진 url에서 파일 데이터를 가져옴.
  4. Blob 변환: 파일 데이터를 Blob 형식으로 변환.
  5. 임시 URL 생성: Blob 데이터를 브라우저에서 접근할 수 있는 URL로 변환.
  6. 다운로드 실행: 동적으로 생성한 <a> 태그를 통해 다운로드 트리거.
  7. 리소스 정리: 메모리 누수를 방지하기 위해 Blob URL 해제.
  8. 오류 처리: 실패 시 사용자에게 알림.
  9. 상태 정리: 진행 상태를 초기화.
수토리지