Second use of input file doesn't trigger onchange anymore

前端 未结 8 1402
旧巷少年郎
旧巷少年郎 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:44

    If you're using React or just javascript in general you can what you can also do is "reset" the value of the event target.

    So If you have something like a component that can upload and "remove" an image:

    <input type="file" onChange={onChange} />
    

    your onChange can be:

    onChange(event) {
    
        const files = event.target.files;
    
        // your logic here on what to do with files (maybe fetch the preview or something)
    
        // this line right below will reset the 
        // input field so if you removed it you can re-add the same file
        event.target.value = ''
    }
    
    0 讨论(0)
  • 2020-12-25 12:47

    TL;DR: Just reset the value attribute to empty("") right after using the file selector (using some event call backs or explicit function call)

    Synch is partially right about onchange event that it will not fire for same file..More precisely onchange in case of input type file(scenario mentioned by ether) considers file location for event triggering.

    ##Try this out after selecting any file In jQuery $("#image_message_upload [type='file']")[0].value

    You will get something like "C:\fakepath\country-and-mobile-redirect-for-wordpress-dwpsxm-clipar.jpg" as output (that is the location of file selected)

    That means either you change the file name or its location, which is not right. So, more logically what we can do while deleting the file is setting input value attribute to empty("")

    $("#image_message_upload [type='file']")[0].value=""

    So adding this line (inside clearPictureAttachment(), as per this question) will reset the file input type and you can select the same image file with no issues.

    Cheers :)

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