[javascript] 파일 선택시 이벤트를 발생시키는 방법

나는 양식을 가지고

<form  onSubmit="return disableForm(this);" action="upload.php" method="post" name="f" id="wizecho" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button onClick="return disableForm(this),ajaxUpload(this.form,'wizecho_upload.php', '&lt;br&gt;Uploading image please wait.....&lt;br&gt;'); return false;">
        Upload Image
    </button>
</form>

이미지를 업로드하는 것입니다.

여기에서 이미지를 업로드하려면 버튼을 클릭해야하며 onClick이벤트 를 사용해야 합니다. 업로드 버튼을 제거하고 입력에서 파일이 선택 되 자마자 이벤트를 시작하고 싶습니다. 어떻게하나요 ??



답변

파일 입력에 변경 이벤트를 사용하십시오.

$("#file").change(function(){
         //submit the form here
 });


답변

입력 필드에서 onchange 이벤트를 구독 할 수 있습니다.

<input type="file" id="file" name="file" />

그리고:

document.getElementById('file').onchange = function() {
    // fire the upload here
};


답변

이것은 수락 답변의 의견에서 위의 @Christopher Thomas의 우려를 해결할 새로운 답변이 필요한 오래된 질문입니다. 페이지를 벗어나지 않고 두 번째로 파일을 선택하는 경우 클릭하거나 터치 스타트 (모바일 용)를 수행 할 때 값을 지워야합니다. 아래는 페이지에서 벗어나 jquery를 사용하는 경우에도 작동합니다.

//the HTML
<input type="file" id="file" name="file" />



//the JavaScript

/*resets the value to address navigating away from the page
and choosing to upload the same file */

$('#file').on('click touchstart' , function(){
    $(this).val('');
});


//Trigger now when you have selected any file 
$("#file").change(function(e) {
    //do whatever you want here
});


답변

파일이 성공적으로로드 된 후 원하는 작업을 수행하십시오. 파일 처리가 완료된 직후 파일 제어 값을 빈 문자열로 설정하십시오. 그래서 .change ()는 파일 이름이 변경 되든 아니든 항상 호출됩니다. 예를 들어 당신은이 일을 할 수 있고 매력처럼 나를 위해 일했습니다.

  $('#myFile').change(function () {
    LoadFile("myFile");//function to do processing of file.
    $('#myFile').val('');// set the value to empty of myfile control.
    });


답변

vue 사용자를위한 솔루션, 동일한 파일을 여러 번 업로드하고 @change 이벤트가 트리거되지 않을 때 문제 해결 :

 <input
      ref="fileInput"
      type="file"
      @click="onClick"
    />
  methods: {
    onClick() {
       this.$refs.fileInput.value = ''
       // further logic for file...
    }
  }


답변

<input type = “file”@ change = “onFileChange”class = “input upload-input”ref = “inputFile”/>

onFileChange(e) {
//upload file and then delete it from input 
 self.$refs.inputFile.value = ''
}


답변

es6를 사용하는 바닐라 js

document.querySelector('input[name="file"]').addEventListener('change', (e) => {
 const file = e.target.files[0];
  // todo: use file pointer
});