본문 바로가기
자바스크립트

[front-end] input type file에서 특정 확장자 제외시키기

by PD su 2023. 3. 16.

txt이외의 파일은 전부 가능한테 txt파일만 제외시켜달라는 요청을 받았다.

<div id="fileComp_${status.index}">
    <input type="file" style="display:none;" id="fileInput_${status.index}" data-index="${status.index}" tabindex='-1'>
    <input type="text" id="fileName_${status.index}" readonly="readonly" onclick="$(fileInput_${status.index}).click();">
    <label for="fileInput_${status.index}" class="btn is-secondary">파일첨부</label>
</div>

위 같은 형태가 n개가 반복되고 그 n개 모두에게 같은 이벤트를 할당해야 하는 상황

 

우선은 페이지가 렌더링 된 후 초기화 할 때 아래와 같이 이벤트를 매핑시켜준다.

$("input[type='file']").change($M.proc.fileChange);

그러고 난 후에 change 이벤트가 발생하면 e.preventDefault를 호출하여도 파일은 이미 첨부된 상태라 의미가 없었다.

 

그래서 해당 input을 부시고 다시 생성하기로 결정

 

$M.proc.fileChange = function(e) {
    if("text/plain".equals(e.target.files[0].type)) {
        var _parent = $("#fileInput_"+$(this).data("index")).parent();
        var _index = $(this).data("index");
        $("#fileInput_"+_index).remove();
         var _html = '<input type="file" class="hd-element" id="fileInput_'+_index+'" data-index="'+_index+'" tabindex="-1">';
        _parent.prepend(_html);
        _parent.children().eq(0).change($M.proc.fileChange);
        e.preventDefault();
        return;
    }

    $("#fileName_"+e.target.dataset.index).get(0).value = e.target.files[0].name;
}

 

 

1. 이벤트 선언

2. change 이벤트로 발생한 파라미터에서 파일 타입 추출 후 text/plain인지 검사

3. input type file의 부모 객체, data들을 메모리에 저장

4. txt 파일이 첨부된 input을 삭제

5. 새로운 input을 str로 생성

6. 삭제한 위치에 삽입

7. 새로 삽입한 객체를 찾아서 이벤트 매핑

 

위 순서로 하면 겉으로 보기엔 삽입하기 전 상태로 보이지만 실제로는 객체가 삭제되었다가 다시 생성되어 깨긋한 상태가 된다.

'자바스크립트' 카테고리의 다른 글

전화번호를 누가 이상하게 넣어놨을때  (0) 2023.02.09