
2025.7.17 목요일의 공부기록
파일이나 Blob 데이터를 브라우저에서 직접적으로 사용하기 어려울 때, 브라우저가 이해할 수 있는 임시 URL을 만들어주는 메서드이다.
URL.createObjectURL(파일 또는 Blob)을 사용하면 데이터를 가리키는 임시 URL이 생성된다.<img>, <a>와 같은 태그의 src나 href에 연결하여 파일을 미리 보거나 다운로드할 수 있다.<input type="file" id="file-input" />
<img id="preview" />
<script>
const fileInput = document.getElementById('file-input');
const preview = document.getElementById('preview');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
const imageUrl = URL.createObjectURL(file);
preview.src = imageUrl;
}
});
</script>
const textData = "Hello World!";
const blob = new Blob([textData], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "hello.txt";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// URL 사용 후 메모리 해제
URL.revokeObjectURL(url);
명시적으로 사용 후에는 반드시 URL.revokeObjectURL(url)을 호출하여 메모리를 해제하는 것이 좋다.