JavaScript

[JavaScript] Spring쇼핑몰 프로젝트 - input태그 파일 이미지 미리 보기

issaac 2021. 12. 13. 12:46

상품 업로드시 대표미이지를 설정해야 하는데

기존 input 태그에서는 이미지 미리보기 기능을 지원하지 않는다.

따라서FileReader()를 통해 input태그에 이미지가 업로드 되면

미리 생성해둔 img 태그의 이미지 경로값을 변경하여

업로드한 이미지가 img태그에 나타나도록 할 것이다.

 

1. 상품 업로드 jsp

1
2
3
4
5
6
7
8
<tr>
    <th style="text-align:center;">대표이미지</th>
    <td class="content"> 
         <img style="width: 400px;" id="dummy-image" 
         src="<%=request.getContextPath()%>/resources/images/goodsupload/dummyImage500X500.png">
         <input type="file" id="gds_thumbnail1" name="gds_thumbnail1">
    </td>
</tr>
cs

우선 미리보기용 img태그와 이미지파일을 올릴 input태그가 필요하다.

img태그에는 더미 이미지파일을 올려두면 다음과 같이 view페이지가 생성된다.

 

 

2. script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function readImage(input) {
    // input 태그에 이미지를 업로드 한 경우
    if(input.files && input.files[0]) {
            // FileReader 생성
            const reader = new FileReader();
            reader.onload = function(e){
                const previewImage = document.getElementById("img태그 id값");
                previewImage.src = e.target.result;
            }
            // reader가 업로드된 이미지의 경로를 읽는다.
            reader.readAsDataURL(input.files[0])
        }
    }
    // input 태그에 change 이벤트 설정
    const inputImage = document.getElementById("input태그 id값");
    inputImage.addEventListener("change"function(e){
        readImage(e.target);
    });
cs

js에서 FileReader() 객체는 비동기적으로 파일의 내용을 가져오는데 사용된다.

readAsDataURL()은 FileReader() 객체와 함께 사용할 수 있는 메소드로

img src속성에 넣을 '업로드한 File의 URL'을 가져올 수 있다.

 

3. 실행화면