728x90
자바스크립트로 파일 드래그 앤 드롭 업로드 방법
이미지를 드래그 앤 드롭 하거나 클릭하여 업로드하세요.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>이미지 업로드</title>
<style>
#drop-area {
border: 2px dashed #ccc;
width: 300px;
height: 200px;
text-align: center;
padding: 10px;
margin: 10px auto;
transition: background-color 0.3s ease-in-out;
}
#drop-area:hover {
background-color: #eee;
}
#image-preview {
margin: 10px auto;
max-width: 100%;
max-height: 200px;
display: none;
}
</style>
</head>
<body>
<div class="container">
<div id="drop-area">
<p>이미지를 드래그 앤 드롭 하거나 클릭하여 업로드하세요.</p>
<input type="file" id="file-input" accept="image/*" style="display: none;">
</div>
<img id="image-preview" src="" alt="업로드된 이미지">
</div>
<script>
const dropArea = document.getElementById("drop-area");
const fileInput = document.getElementById("file-input");
const imagePreview = document.getElementById("image-preview");
// 드래그 앤 드롭 이벤트 처리
dropArea.addEventListener("dragover", (e) => {
e.preventDefault();
dropArea.style.backgroundColor = "#eee";
});
dropArea.addEventListener("dragleave", () => {
dropArea.style.backgroundColor = "#fff";
});
dropArea.addEventListener("drop", (e) => {
e.preventDefault();
dropArea.style.backgroundColor = "#fff";
const file = e.dataTransfer.files[0];
if (file && file.type.startsWith("image")) {
displayImage(file);
}
});
// 파일 입력 필드 변경 이벤트 처리
fileInput.addEventListener("change", () => {
const file = fileInput.files[0];
if (file && file.type.startsWith("image")) {
displayImage(file);
}
});
// 클릭 이벤트 처리
dropArea.addEventListener("click", () => {
fileInput.click();
});
// 이미지 표시 함수
function displayImage(file) {
const reader = new FileReader();
reader.onload = () => {
imagePreview.src = reader.result;
imagePreview.style.display = "block";
};
reader.readAsDataURL(file);
}
</script>
</body>
</html>
728x90
'javascript' 카테고리의 다른 글
자바스크립트로 정규 표현식 (Regular expression) 테스트 (1) | 2023.10.03 |
---|---|
자바스크립트(javascript) 클래스(Class) 알아보기 (0) | 2023.10.01 |
자바스크립트(Javascript) 변수 기본 (1) | 2023.10.01 |
자바스크립트로 프로그레스바 만들기 (0) | 2023.09.02 |
티스토리에서 자바스크립트로 클립보드 복사 만들기 (0) | 2022.10.25 |