URL.createObjectURL()로 파일 미리보기 구현

Odyssey·2025년 7월 17일
0

Next.js_study

목록 보기
57/58
post-thumbnail

2025.7.17 목요일의 공부기록

URL.createObjectURL() 이란?

파일이나 Blob 데이터를 브라우저에서 직접적으로 사용하기 어려울 때, 브라우저가 이해할 수 있는 임시 URL을 만들어주는 메서드이다.

🔗 MDN 공식 문서

동작 방식

  1. 파일을 선택하거나 JavaScript로 Blob 데이터를 생성하면, 브라우저가 바로 사용할 수 없다.
  2. URL.createObjectURL(파일 또는 Blob)을 사용하면 데이터를 가리키는 임시 URL이 생성된다.
  3. 이 URL을 <img>, <a>와 같은 태그의 srchref에 연결하여 파일을 미리 보거나 다운로드할 수 있다.
  4. 브라우저를 닫거나 새로고침하면 임시 URL이 자동으로 사라진다.

사용 예시

이미지 미리보기 예시 코드

<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)을 호출하여 메모리를 해제하는 것이 좋다.

0개의 댓글