라이브러리

fullcalendar datepicker autocomplete sweetAlert file preview modal loading sortable

file preview

html

<div class="js-file-box">
    <!-- data-file 값이 매칭되어야 함 -->
    <input type="file" title="파일 업로드" accept="image/png, image/gif, image/jpeg, image/jpg" onchange="uploadFile(this);" data-file="1" class="js-file-item">
    <div class="js-file-img-box" data-file="1"></div>
</div>

script

// 이미지 파일 미리보기
function uploadFile(target) {
    const $imgFile = $(target).data("file"),
        $imgBox = $(".js-file-img-box[data-file='"+$imgFile+"']");
    if (target.files && (target.files[0])) {
        const fileReader = new FileReader();
        fileReader.onload = function(e) {
            let html = "";
            html += "<div class='js-file-img'>";
            html += "<img src='"+e.target.result+"'>";
            html += "<button type='button' class='del' onclick='uploadFileDel(this);'>삭제</button>";
            html += "</div>";
            $imgBox.find(".js-file-img").remove();
            $imgBox.append(html);
        };
        fileReader.readAsDataURL(target.files[0]);
    }
}

// 이미지 파일 미리보기 삭제
function uploadFileDel(target) {
    const $imgBox = $(target).closest('.js-file-img-box'),
        $data = $imgBox.data("file");
    $(".js-file-item[data-file='"+$data+"']").val("");
    $imgBox.html("");
}