본문 바로가기

일하면서배운것

html input type = "file" 확장자 제한/ 파일 업로드 제한

input 타입이 파일인 경우 이미지 파일만 업로드하고 이외는 막아 달라는 요구사항이 있었다.

따라서 input 태그에 accept="image/*" 를 추가하고

 자바스크립트 코드 onchange="validation(this)" 를 추가했다.

input 태그에 accept는 파일 열기를 눌렀을 때 해당 확장자로 자동으로 선택이 되도록 하는 것

자바스크립트 코드는 확장자가 정규식에서 넣은 확장자가 아닐 경우 알럿창을 띄운다.

  <input type="file" accept="image/*" onchange="validation(this)" >
  
  
  <script language="javascript">
//파일 확장자 체크
function validation(file) {
    var file_path = file.value;
    var reg = /(.*?)\.(jpg|bmp|jpeg|png|gif|GIF|PNG|JPG|JPEG|BMP)$/;

    if (file_path != "" && (file_path.match(reg) == null || reg.test(file_path) == false)) {
        file.value = "";
        alert("이미지 파일만 업로드 가능합니다.");
    }
}
</script>

 

 

 

 

참고 글

https://jinjuu.tistory.com/5

https://ssungkang.tistory.com/entry/html-input-%E1%84%91%E1%85%A1%E1%84%8B%E1%85%B5%E1%86%AF-%E1%84%8E%E1%85%A5%E1%86%B7%E1%84%87%E1%85%AE%E1%84%89%E1%85%B5-%E1%84%91%E1%85%A1%E1%84%8B%E1%85%B5%E1%86%AF-%E1%84%92%E1%85%AA%E1%86%A8%E1%84%8C%E1%85%A1%E1%86%BC%E1%84%8C%E1%85%A1-%E1%84%8C%E1%85%A6%E1%84%92%E1%85%A1%E1%86%AB%E1%84%92%E1%85%A1%E1%84%80%E1%85%B5

 

[JS] input type="file" 확장자 제한, 초기화

input type="file" 요소의 확장자는 기본적으로 'accept' 속성을 이용하여 제한할 수 있다. [html](https://www.w3schools.com/tags/att_input_accept.asp 참조) 다만, IE9 이하일때는 지원되지 않는 속성이며파일 선택 시

jinjuu.tistory.com