TypeScript·
downloadFile
- #TypeScript
- #Snippets
downloadFile
브라우저에서 파일을 다운로드하는 유틸리티 함수입니다. Blob이나 MediaSource 객체를 받아서 지정된 파일명으로 다운로드합니다.
매개변수
| 매개변수 | 타입 | 필수 | 설명 |
|---|---|---|---|
file | Blob | MediaSource | ✅ | 다운로드할 파일 객체 |
filename | string | ✅ | 다운로드될 파일명 |
코드
1export const downloadFile = (file: Blob | MediaSource, filename: string) => {2const url = URL.createObjectURL(file);3const a = document.createElement("a");4a.href = url;5a.download = filename;6a.click();7URL.revokeObjectURL(url);8};
사용법
1// 텍스트 파일 다운로드2const textContent = "Hello, World!";3const blob = new Blob([textContent], { type: 'text/plain' });4downloadFile(blob, 'hello.txt');56// JSON 파일 다운로드7const jsonData = { name: "John", age: 30 };8const jsonBlob = new Blob([JSON.stringify(jsonData, null, 2)], { type: 'application/json' });9downloadFile(jsonBlob, 'data.json');1011// 이미지 파일 다운로드12fetch('https://example.com/image.jpg')13.then(response => response.blob())14.then(blob => {15downloadFile(blob, 'downloaded-image.jpg');16});