createObjectURL / revokeObjectURL

킴지·2023년 9월 20일

React

목록 보기
4/4

createObjectURL

URL.createObjectURL(objectUrl)

blob 객체를 가리키는 URL을 만들어 준다. URL은 자신을 생성한 브라우저의 창이 닫히면 무효화된다.

revokeObjectURL

URL.revokeObjectURL(objectUrl)

createObjectURL로 생성한 URL을 해제한다. URL을 더는 쓸 일이 없을 때, 브라우저에게 해당 객체를 더 이상 기억할 필요없다고 알려주는 것이다.

사용예시

react/typescript 환경에서 이미지 파일 업로드하기

import React, { useEffect, useRef, useState } from "react"

const App = () => {
	const [userPhoto, setUserPhoto] = useState<string[]>([])
	let photoUrl: string | undefined
    
    useEffect(() => {
    	// 언마운트 시 url 무효화
    	return () => {
        	if (photoUrl !== undefined){
            	URL.revokeObjectURL(photoUrl)
            }
        }
    }, [photoUrl])
    
    const handleUploadPhoto = (e: React.ChangeEvent<HTMLInputElement>) => {
    	if (!e.target.files){
        	return
        }
        
        const blob = new Blob([e.target.files[0]], {type: "image/png"})
        photoUrl = URL.createObjectURL(blob)
        setUserPhoto([...userPhoto, photoUrl])
    }
    
	return (
    	<div>
        	{userPhoto.map((photo, index) => (
            	<div key={index}>
                	<img src={photo} alt="" />
                </div>
            ))}
            <input type="file" onChange={handleUploadPhoto} />
        </div>
    )
}

export default App
profile
서울생 도시녀의 전국구 플로우 ෆ

0개의 댓글