이미지 업로드 미리보기 구현

HTML

<div class="image-container" id="imageBox">
     <img src="https://placehold.co/600x400?text=sample+image" id="previewImage">
</div>

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

CSS

.image-container {
     width: 300px;
     height: 200px;
     border: 2px dashed #ccc;
     display: flex;
     justify-content: center;
     align-items: center;
     cursor: pointer;
     overflow: hidden;
     border-radius: 10px;
     transition: border 0.3s;
}

.image-container:hover {
     border-color: #888;
}

.image-container img {
     width: 100%;
     height: 100%;
     object-fit: cover;
}

#imageInput {
     display: none;
}

JS

$(document).ready(function () {
     $("#imageBox").on("click", function () {
          $("#imageInput").click(); // 파일 선택 창 열기
     });

     $("#imageInput").on("change", function (event) {
          const file = event.target.files[0];
          if (file && file.type.startsWith("image/")) {
               const reader = new FileReader();
               reader.onload = function (e) {
                    $("#previewImage").attr("src", e.target.result); // 미리보기 변경
               };
               reader.readAsDataURL(file);
          }
     });
});

See the Pen Untitled by Juyeon (@Juyeon) on CodePen.