TypeScript·

downloadFile

  • #TypeScript
  • #Snippets

downloadFile

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

매개변수

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

코드

1
export const downloadFile = (file: Blob | MediaSource, filename: string) => {
2
const url = URL.createObjectURL(file);
3
const a = document.createElement("a");
4
a.href = url;
5
a.download = filename;
6
a.click();
7
URL.revokeObjectURL(url);
8
};

사용법

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