Chrome file upload bug: on change event won't be executed twice with the same file

laukok picture laukok · Feb 6, 2012 · Viewed 13.5k times · Source

I am working on this html5 file uploader plugin but it has a bug on Google Chrome which I can't understand and fix it. It works fine on Firefox.

jsfiddle link

The problem is that you cannot upload the same file twice from your desktop.

When you first click, select, and hit OK to upload a file from your desktop, it should alert a message, for instance '.button-1' - depends on which upload button you click.

Then if you try to upload the same file again, this line of code won't be executed anymore,

$(".upload-file",object_parent).change(function() {

             ...
             ...

             alert($cm.selector);

});

Any idea what goes wrong in this plugin?

(function($){

    // Attach this new method to jQuery
    $.fn.extend({ 

        // This is where you write your plugin's name
        upload_file_html5: function(options) {

            // Set the default values, use comma to separate the settings, example:
            var defaults = {
                objectSuperparent:    '.media'
            }

            var options =  $.extend(defaults, options);
            var o = options;

            var $cm = this.click(function(e){

                // <a> button is the object in this case.
                var object = $(this);

                // Get other info from the element belong to this object group.
                var object_href = object.attr('href');
                var object_parent = object.parent();
                alert($cm.selector);

                // Trigger the click event on the element.
                // Due to security policies triggering click on the input type=file is not allowed/supported in some browsers and Opera is one of them.
                //$('input[type=file]').trigger('click'); // or:
                $(".upload-file",object_parent).click();

                return false;

            });

            // Trigger ajax post when ever the file is changed by the user.
            var $cm_2 = $(".upload-file").change(function(){

                // <input> is the object in this case.
                var object = $(this);

                var object_form = object.parent();
                var object_superparent = object.parents(o.objectSuperparent);
                var path_config = $($cm.selector,object_superparent).attr('href');
                var path_post = object_form.attr('action');

                alert($cm.selector);
                //alert(path_config);

                ....
                ....

            });

        }
    });

})(jQuery);

It was working OK on Chrome but just failed recently, probably Chrome has updated a latest version to my machine and this update causes the bug?

Answer

fundon picture fundon · Jul 1, 2012

If you want to upload twice, clear file input value

$('input[type="file"]').val(null);

jsfiddle test