프론트엔드💛

[Vue3] 입력 받은 이미지 preview(썸네일) 보여주기

dalin❤️ 2022. 9. 13. 22:01

상황

회사에서 이미지를 입력 받아서, 그 이미지를 화면에 보여주는 작업을 해야 했다. (하나의 이미지만)
전에 토이 프로젝트를 할 때, 프로필 이미지를 바꾸는 작업을 할 때 이미지 입력 받는 걸 했던 생각이 났다.
이미지 입력 받는 것은 아래와 같이 input 을 사용했다.

<input type="file" accept="image/*">

그런데 preview를 보여주는 건 안해봐서 감이 안왔다..
다행히 찾아보니 예시 코드들이 있었고, mdn 사이트 - 사용자가 선택한 이미지의 섬네일 보여주기 에서도 친절하게 설명해줬다 ~

코드와 설명

vue의 template부분(html)에 이미지를 보여줄 div 영역을 만들어 두기.

// 이미지 파일을 입력받기. 입력 받으면 changeImage 함수 실행
<input type="file" accept="image/*" @change="changeImage"/> 

<div class="preview"> // class를 이용해서 적절한 style을 주기        
	<img :src="previewImage"/> //ref previewImage가 바뀌면 반영됨.
 </div>

vue script부분에

const previewImage = ref<string>('')  // vue ref- 반응형 값을 저장

const changeImage = (event) => { 
    const files = event.target?.files
    if (files.length > 0){
        const file = files[0]

		// FileReader 객체 : 웹 애플리케이션이 데이터를 읽고, 저장하게 해줌
        const reader = new FileReader() 
		
        // load 이벤트 핸들러. 리소스 로딩이 완료되면 실행됨.
        reader.onload = (e) => {
        previewImage.value = e.target.result } // ref previewImage 값 변경
		
        // 컨텐츠를 특정 file에서 읽어옴. 읽는 행위가 종료되면 loadend 이벤트 트리거함 
        // & base64 인코딩된 스트링 데이터가 result 속성에 담김
        reader.readAsDataURL(file)

    }
}

참고 자료

https://developer.mozilla.org/ko/docs/Web/API/File_API/Using_files_from_web_applications#%EC%98%88%EC%8B%9C_%EA%B0%9D%EC%B2%B4_url%EC%9D%84_%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC_%EC%9D%B4%EB%AF%B8%EC%A7%80_%ED%91%9C%EC%8B%9C%ED%95%98%EA%B8%B0

 

웹 어플리케이션에서 파일 사용하기 - Web API | MDN

HTML5의 DOM으로 추가된 File API를 사용하여, 이제 웹 컨텐츠가 사용자에게 로컬 파일을 선택한 후 파일의 컨텐츠를 읽도록 요청할 수 있습니다. 이 선택은 HTML <input> 엘리먼트나 드래그 앤 드랍을

developer.mozilla.org

https://gist.github.com/zmts/9cfdba90897db1615b6e9fda6069a124

 

Vue.js Preview image file

Vue.js Preview image file. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

728x90