how to fire event on file select

前端 未结 7 1026
遥遥无期
遥遥无期 2020-12-02 15:25

I\'ve a form as

相关标签:
7条回答
  • 2020-12-02 15:29

    vanilla js using es6

    document.querySelector('input[name="file"]').addEventListener('change', (e) => {
     const file = e.target.files[0];
      // todo: use file pointer
    });
    
    0 讨论(0)
  • 2020-12-02 15:34

    Solution for vue users, solving problem when you upload same file multiple times and @change event is not triggering:

     <input
          ref="fileInput"
          type="file"
          @click="onClick"
        />
      methods: {
        onClick() {
           this.$refs.fileInput.value = ''
           // further logic for file...
        }
      }
    
    0 讨论(0)
  • 2020-12-02 15:40

    You could subscribe for the onchange event on the input field:

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

    and then:

    document.getElementById('file').onchange = function() {
        // fire the upload here
    };
    
    0 讨论(0)
  • 2020-12-02 15:43

    <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 = ''
    }
    
    0 讨论(0)
  • This is an older question that needs a newer answer that will address @Christopher Thomas's concern above in the accept answer's comments. If you don't navigate away from the page and then select the file a second time, you need to clear the value when you click or do a touchstart(for mobile). The below will work even when you navigate away from the page and uses 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
    });
    
    0 讨论(0)
  • 2020-12-02 15:46

    Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm

      $('#myFile').change(function () {
        LoadFile("myFile");//function to do processing of file.
        $('#myFile').val('');// set the value to empty of myfile control.
        });
    
    0 讨论(0)
提交回复
热议问题