Snippets

downloadFile

#TypeScript#Utility#Browser

downloadFile

브라우저에서 파일을 다운로드하는 유틸리티 함수입니다. Blob이나 MediaSource 객체를 받아서 지정된 파일명으로 다운로드합니다.

매개변수

매개변수타입필수설명
fileBlob | MediaSource다운로드할 파일 객체
filenamestring다운로드될 파일명

코드

export const downloadFile = (file: Blob | MediaSource, filename: string) => {
  const url = URL.createObjectURL(file);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
};

사용법

// 텍스트 파일 다운로드
const textContent = "Hello, World!";
const blob = new Blob([textContent], { type: 'text/plain' });
downloadFile(blob, 'hello.txt');
 
// JSON 파일 다운로드
const jsonData = { name: "John", age: 30 };
const jsonBlob = new Blob([JSON.stringify(jsonData, null, 2)], { type: 'application/json' });
downloadFile(jsonBlob, 'data.json');
 
// 이미지 파일 다운로드
fetch('https://example.com/image.jpg')
  .then(response => response.blob())
  .then(blob => {
    downloadFile(blob, 'downloaded-image.jpg');
  });