Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

(❀╹◡╹)

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

Programing/WEB

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

진 주 2018. 12. 28. 11:37

input type="file" 요소의 확장자는 기본적으로 'accept' 속성을 이용하여 제한할 수 있다.


[html]

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

(https://www.w3schools.com/tags/att_input_accept.asp 참조)





다만, IE9 이하일때는 지원되지 않는 속성이며

파일 선택 시 확장자를 모든 파일로 변경하면 다른 파일의 선택이 가능하므로

script에서의 제어가 필요하다.



[script]

$(document).on("change", "input[type='file']", function(){

var file_path = $(this).val();

var reg = /(.*?)\.(jpg|bmp|jpeg|png)$/;

  // 허용되지 않은 확장자일 경우

if (file_path != "" && (file_path.match(reg) == null || reg.test(file_path) == false)) {

if ($.browser.msie) { // ie 일때 

$(this).replaceWith($(this).clone(true));

} else {

$(this).val("");

}

alert("이미지 파일만 업로드 가능합니다.");

}

});



--------------------------------------------------------------------

또는 아래와 같이 요소에 onchange 함수를 명시하여 사용해도 된다.

--------------------------------------------------------------------



[html]

<input type="file" onchange="validation(this);" />


[script]

function validation(file) {

 var file_path = file.value;

var reg = /(.*?)\.(jpg|bmp|jpeg|png)$/;

        // 허용되지 않은 확장자일 경우

if (file_path != "" && (file_path.match(reg) == null || reg.test(file_path) == false)) {

if ($.browser.msie) { // ie 일때 

file.parentNode.replaceChild(file.cloneNode(), file);

} else {

file.value = "";

}

alert("이미지 파일만 업로드 가능합니다.");

}

}



* 부가설명

- $(document).on("change", "input[type='file']", function(){

  → 동적으로 태그가 생성 및 삭제되는 경우에 사용


$("[type='file']").change(function(){

  → 태그가 고정되어 있는 경우 위와 같이 사용해도 무방


jpg|bmp|jpeg|png

  → 허용하고자 하는 확장자로 변경하여 사용


① $(this).replaceWith($(this).clone(true));

  ② file.parentNode.replaceChild(file.cloneNode(), file);

  → jquery를 사용했을 경우()그렇지 않은 경우() 다르게 사용



'Programing > WEB' 카테고리의 다른 글

[ASP] 변수 선언 (Dim, ReDim)  (0) 2019.09.10
[ASP] IP 확인  (0) 2019.09.10
[ASP] Response.Expires 설정  (0) 2019.09.09
[PHP] 특정 IP에서만 작동하도록  (0) 2019.05.15
[PHP + JS] select2 data ajax 처리  (0) 2018.12.27