상현에 하루하루
개발자의 하루

input file 업로드 취소 이벤트 js로 감지

( 업데이트: )

파일 인풋을 동적으로 만드는 상황에서 파일을 선택하지 않고 취소했을때 인풋을 제거해야하는 상황이 생겼다. 이러한 상황은 JS로 어떻게 처리해야할까?

input file cancel 감지

<input type="file" id="theFile" />Code language: HTML, XML (xml)
var theFile = document.querySelector('#theFile');

theFile.on('click', initialize);

function initialize(event) {
    document.body.onfocus = checkIt;
    console.log('initializing');
}

function checkIt() {
    if (theFile.value.length) {
        aleft('Files Loaded');
    } else {
        alert('Cancel clicked');
    }
    // 초기화
  document.body.onfocus = null;
    console.log('checked');
};Code language: JavaScript (javascript)

initialize()

  • theFile의 클릭이벤트로 사용할 함수
  • document.body.onfocus = checkIt 이벤트를 추가해서 cancel 이벤트를 감지

checkIt()

  • 사용자가 파일을 업로드할 때 파일 길이는 File.value.length 속성을 사용하여 찾습니다. 이 값이 0이 아니게 되면 조건이 충족되고 “파일 로드됨”을 표시한다
  • 사용자가 파일을 업로드하지 않으면 파일 길이의 값은 0이다. 이로 인해 조건이 충족되지 않고 “클릭 캔슬”이라는 경고 상사자 나타난다