jquery

[jQuery] 이미지 업로드시 미리보기 기능 구현하기 - 이미지 등록

http://portfolio.wonpaper.net 2024. 7. 12. 16:04

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<div class="work_place02">
    <form id="f1" name="f1" method="post" enctype="multipart/form-data">
 
        <div class="upload-box">
            <div id="drop-file" class="drag-file">
                <img src="/image/upload_icon.png" alt="파일 아이콘" class="image">
                <p class="message">(10MB 이하 업로드)</p>
                <label class="file-label" for="chooseFile">사진첩에서 사진 가져오기</label>
                <input class="file" id="chooseFile" type="file" name="userfile1" accept="image/*" onchange="dropFile.handleFiles(this.files)">
 
            </div>
            <button type="button" class="del"><img src="/image/work_place_icon5.png" alt=""></button>
        </div>
        <span style="color:red; margin: 10px 0 0 0; display: block;">(*) 중앙에 '사진첩에서 사진 가져오기' 버튼을 누르시고 이미지를 첨부해주세요.</span>
 
    </form>
</div>
 
<script>
 
    const fileImage = document.getElementById("chooseFile");
    const filePreview = document.querySelector('.work_place02 .upload-box');
    const fileMaxsize = 10 * 1024 * 1024;
 
    fileImage.onchange = function () {
        const reader = new FileReader();
 
        reader.onload = function (e) {
            const fileSize = fileImage.files[0].size;
            if(fileSize > fileMaxsize) {
                alert('10MB 이하의 사진만 업로드 가능합니다.');
                fileImage.value="";
                return;
            } else {
            }
 
            // get loaded data and render thumbnail.
            filePreview.style.backgroundImage  = "url("+e.target.result+")";
            console.log(e.target.result);
            filePreview.classList.add("has-image");
            if ($(filePreview).hasClass("has-image")) {
                console.log('사진있음');
                $(filePreview).find('.del').show();
                $(filePreview).find('.del').click(function(){
                    fileImage.value="";
                    $(filePreview).removeClass('has-image');
                    $(this).hide();
                })
            }
        };
        
        // 올린 이미지 삭제기능
        $(filePreview).find('.del').click(function (event) {
            event.preventDefault(); // 기본 동작 방지
            $(filePreview).css("background-image""none"); // 선택된 이미지 제거
            fileImage.value = ''// 파일 입력 필드 초기화
            $(filePreview).removeClass('has-image');
            $(this).hide();
            $("#drop-file").css("display","block");
        });
 
        // read the image file as a data URL.
        reader.readAsDataURL(this.files[0]);
        $("#drop-file").css("display","none"); // 이미지 첨부하면 안내문구 숨기기
    };
 
</script>
cs