Second use of input file doesn't trigger oncha

2020-02-23 07:10发布

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 because the onChange event is not triggered. Why is that so?

Here is a use case:
1. On click of the button, I call uploadMessagePicture(), which opens the browse window.
2. When the user has selected a picture, a onChange event is detected which triggers the ajaxFileUpload() and shows the photo editor area.
3. When the upload is complete, a preview of the image is shown. 4. The user deletes the picture by calling deleteMessageImage() (which also clears the fields and hides the photo editor).
5. The user tries to upload another picture.

At this point, the browse window appears, but when I select a picture, the onChange event is not triggered so nothing happens... (Also, it doesn't seem like the filename is even transfered to the input' value field.)
I'm on Firefox 23.0.1

Here is the HTML:

<a class="im-photo-btn" href="javascript:;" onclick="javascript:uploadMessagePicture();"><i class="icon-join-photo"></i></a>

<div class="editor-photoarea" id="editor-photoarea" style="display:none;">
    <input name="image_message_file" type="hidden" id="image_message_file" value="" />
    <div id="image_message_upload">
        <input name="image-message" type="file" id="image-message" style="display:none; visibility:hidden;" /> 
        <!-- hide it and trigger it from the photo btn (need both display:none + visibility:hiden for browser compatibility) -->
    </div>
    <div class="loading" id="image_message_loading" style="display:none;"><img alt="<?php echo $lang["Loading"];?>" src="lib/immedia/img/ajax-loader.gif" /> <?php echo $lang["Loading"];?></div>
    <div class="preview" style="display:none;" id="image_message_preview">
        <!-- <div>Image preview :</div>
        <div id='small_message_msg'></div>
            <img src='' />
            <div class='btnoptions'>
                <a onclick='javascript:deleteMessageImage();' href='javascript:;' class='button' title="Delete photo">
                    <span class='ui-icon ui-icon-closethick smsg'></span>Delete
                </a>
         </div>-->
</div>

Here is the javascript to automatically upload the picture

$(document).ready(function (){
    $("#image-message").on('change', function () {
        $('#editor-photoarea').show();
        ajaxFileUploadMessagePicture();
    });
});

function uploadMessagePicture(){
    //trigger the browse click
    if($('#image_message_file').val() == ''){
        //let the person upload a file only if none are there
        $('#image-message').trigger('click');
    }
}

function ajaxFileUploadMessagePicture(){
$("#msg_error_no_image_message").hide();

var imageName = $("#image-message").val();
if(imageName != ''){
    $("#image_message_loading").show();
    $('#sendBtn').attr('disabled', 'disabled');

    $.ajaxFileUpload
    (
        {
            url:siteRegionDir+'lib/immedia/uploadMessagePicture.php',
            secureuri:false,
            fileElementId:'image-message',
            dataType: 'json',
            success: function (data, status)
            {
                updateMessagePicture(data);             
            },
            error: function (data, status, e)
            {
                alert(e);
            }
        }
    )   
}else{
    $("#msg_error_no_image_message").show();
}
return false;
}

Here is the Javascript to delete the picture and clear the fields

function deleteMessageImage(){
//delete the image
var file = $("#image_message_file").val();

if(file != '') {
    $.post(siteRegionDir+'lib/immedia/deleteMessagePicture.php',{filename:file}, function(data) {   
            clearPictureAttachment();               
            $('#editor-photoarea').hide();//make sure it is hidden
        },"html"  
    );
}else{      
    clearPictureAttachment();
    $('#editor-photoarea').hide();//make sure it is hidden
}
}

function clearPictureAttachment(){
//var control = $("#image-message");
$("#image-message").attr('value', '');
//control.replaceWith( control = control.clone( true ) );//so it resets it all, truw = keep the bound events
$("#image_message_file").attr('value', '');
$("#image_message_loading").hide();
$("#image_message_upload").show();
$("#image_message_preview").hide();
}

Any help would be great! Thanks!

7条回答
▲ chillily
2楼-- · 2020-02-23 07:48

@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.

查看更多
forever°为你锁心
3楼-- · 2020-02-23 07:53

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 :)

查看更多
倾城 Initia
4楼-- · 2020-02-23 07:54

In angular

HTML

<input #photoInput type="file" /> 

TS

export class SomeComponent {

 @ViewChild('photoInput') photoInput;

 clearPictureAttachment() {
  this.photoInput.nativeElement.value = '';
 }
}
查看更多
Evening l夕情丶
5楼-- · 2020-02-23 07:58

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!

查看更多
不美不萌又怎样
6楼-- · 2020-02-23 08:01

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 = ''
}
查看更多
混吃等死
7楼-- · 2020-02-23 08:02

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

查看更多
登录 后发表回答