Second use of input file doesn't trigger onchange anymore

前端 未结 8 1401
旧巷少年郎
旧巷少年郎 2020-12-25 11:55

I have a picture upload button that automatically uploads the file when selected from the browse window.
Nonetheless, it doesn\'t work the second time around and that is

相关标签:
8条回答
  • 2020-12-25 12:25

    Easiest way to fix this is to add an onclick and set the value to null every time.:

    <input name="fileUpload" type="file" onclick="this.value = null"/>
    
    0 讨论(0)
  • 2020-12-25 12:33

    In angular

    HTML

    <input #photoInput type="file" /> 
    

    TS

    export class SomeComponent {
    
     @ViewChild('photoInput') photoInput;
    
     clearPictureAttachment() {
      this.photoInput.nativeElement.value = '';
     }
    }
    
    0 讨论(0)
  • 2020-12-25 12:34

    After you have done what you want to do with the file, you can reset the FileList.

    In my React app I have this:

    const handleLoad = evt => {
      if (evt.target.files && evt.target.files[0]) {
        dispatch(loadFile(evt.target.files[0].path));
      }
      // Reset the FileList, as otherwise the second and subsequent times
      // we browse, nothing will happen, because nothing changed.
      evt.target.files = new FileList();
    };
    
    0 讨论(0)
  • 2020-12-25 12:36

    Thanks to codingrhythm for leading me on the right track.
    What I did was to actually just add the on("change") call again on the field.
    So I only altered the clearPictureAttachment() function (called when deleting a picture) to this:

    function clearPictureAttachment(){
    $("#image-message").attr('value', '');    
    $("#image_message_file").attr('value', '');
    $("#image_message_loading").hide();
    $("#image_message_upload").show();
    $("#image_message_preview").hide();
    //reenable the onchange to upload a picture
    $("#image-message").on('change', function () {
        $('#editor-photoarea').show();
        ajaxFileUploadMessagePicture();
    });
    }
    

    Thanks again!

    0 讨论(0)
  • 2020-12-25 12:37

    My guess is that you test your functionality with the same picture file over and over again.

    If you select the same file, the onChange event of input[type=file] will not fire.

    Different file with the same name would not fire the event as well. Select a different image file - it will happen.

    To avoid this you can reset the form to ensure that choosing a file will be performed on a clean file control

    0 讨论(0)
  • 2020-12-25 12:39

    @Sync gave me the idea to solve this issue.

    Here is the working code, what you need to do is to clone the file input.

    var control = $('input[type=file]');
    control.replaceWith( control = control.clone( true ) );
    

    and the event will still be fired on second time.

    0 讨论(0)
提交回复
热议问题