자바스크립트로 파일 첨부 체크하는 방법 (input type="file")
회원가입, 게시판 글쓰기, 이미지 업로드 등에서 파일 첨부를 확인해야 하는 상황이 자주 있습니다.
이번 글에서는 JavaScript로 파일 첨부 여부를 체크하는 간단하고 실용적인 예제를 소개합니다.
✔ 왜 파일 첨부 체크가 필요할까요?
사용자가 파일 첨부를 깜빡하고 제출하면 오류가 날 수 있기 때문에,
JavaScript를 이용해 미리 첨부 여부를 확인하면 더 좋은 UX(User Experience)를 제공합니다.
📌 기본 HTML 구조
<form id="uploadForm">
<input type="file" id="myFile">
<button type="submit">업로드</button>
</form>
input type="file"을 사용하면 사용자가 파일을 선택할 수 있습니다.
📁 JavaScript로 파일 첨부 체크하기
document.getElementById("uploadForm").addEventListener("submit", function(e) {
const fileInput = document.getElementById("myFile");
if (!fileInput.value) {
alert("파일을 첨부해주세요.");
e.preventDefault(); // 폼 전송 막기
}
});
설명:
fileInput.value
가 비어 있으면 파일이 선택되지 않은 상태- 그럴 경우
alert()
를 띄우고e.preventDefault()
로 폼 전송을 막습니다
📌 파일 확장자까지 체크하는 예제
document.getElementById("uploadForm").addEventListener("submit", function(e) {
const fileInput = document.getElementById("myFile");
const filePath = fileInput.value;
const allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
if (!filePath) {
alert("파일을 첨부해주세요.");
e.preventDefault();
} else if (!allowedExtensions.exec(filePath)) {
alert("이미지 파일(jpg, png, gif)만 업로드 가능합니다.");
fileInput.value = "";
e.preventDefault();
}
});
이 코드의 장점: 이미지 파일 외에는 업로드되지 않도록 제한할 수 있습니다.
💡 팁: input 태그에 accept 속성도 함께 사용하기
<input type="file" accept="image/*" id="myFile">
accept
속성을 사용하면 사용자가 선택 가능한 파일 형식을 제한할 수 있어요.
🔍 요약 정리
- JavaScript로 파일 첨부 여부를 확인하면 사용자 실수를 줄일 수 있습니다.
fileInput.value
가 비어 있는지 체크하세요.- 정규식으로 확장자 제한도 함께 적용하면 더 안전합니다.
accept
속성으로 프론트에서 힌트를 줄 수 있습니다.
📚 함께 보면 좋은 글
✍ 마무리
파일 첨부 체크는 기초적인 JavaScript 실습으로도 아주 좋은 주제입니다.
앞으로 파일 미리보기, Drag & Drop 업로드 기능도 함께 배워보세요!