[컴] html5 에서 drag & drop image upload 만들기

drag and drop image upload /html5, js / 드래그앤드랍 / 이미지 업로드 / image

html5 에서 drag & drop image upload 만들기

<!DOCTYPE  html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">

body{
  display: flex;
  background: black;
}
.drag-area{
  border: 2px dashed #fff;
  height: 500px;
  width: 700px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.drag-area.active{
  border: 2px solid #fff;
}
.drag-area .icon{
  font-size: 100px;
  color: #fff;
}
.drag-area header{
  color: #fff;
}
.drag-area span{
  color: #fff;
  margin: 10px 0 15px 0;
}
.drag-area button{
  padding: 10px 25px;
  border: none;
  cursor: pointer;
}
.drag-area img{
  height: 100%;
  width: 100%;
  object-fit: cover;
  border-radius: 5px;
}

</style>
</head>
<body>
  <div class="drag-area">
    <div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
    <header>Drag & Drop to Upload File</header>
    <span>OR</span>
    <button>Browse File</button>
    <input type="file" hidden>
  </div>

<script type="text/javascript">
  //selecting all required elements
const dropArea = document.querySelector(".drag-area"),
dragText = dropArea.querySelector("header"),
button = dropArea.querySelector("button"),
input = dropArea.querySelector("input");

button.onclick = ()=>{
  input.click();
}

input.addEventListener("change", function(){
  // if the user select a file with 'Browse File' button
  dropArea.classList.add("active");
  displayFile(this.files[0]);
});


dropArea.addEventListener("dragover", (event)=>{
  // drag over case
  event.preventDefault(); //preventing from default behaviour
  dropArea.classList.add("active");
  dragText.textContent = "Release to Upload File";
});

dropArea.addEventListener("dragleave", ()=>{
  // drag over --> drag leave
  dropArea.classList.remove("active");
  dragText.textContent = "Drag & Drop to Upload File";
});


dropArea.addEventListener("drop", (event)=>{
  // if the user drop a file
  event.preventDefault();
  displayFile(event.dataTransfer.files[0]); //calling function
});

function displayFile(file) {
  let fileType = file.type
  let validTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp']
  if (validTypes.includes(fileType)) {
    // in case of image file
    let freader = new FileReader()
    freader.onload = () => {
      // add a image tag to show the image read
      let base64ImageDataUrl = freader.result
      let imgTag = `<img src="${base64ImageDataUrl}" alt="">`
      dropArea.innerHTML = imgTag
    }
    freader.readAsDataURL(file)
  } else {
    alert('This is not an Image File!')
    dropArea.classList.remove('active')
    dragText.textContent = 'Drag & Drop to Upload File'
  }
}

</script>
</body>

</html>


Reference

  1. Drag & Drop or Browse - File upload Feature in JavaScript

댓글 없음:

댓글 쓰기