user648340
user648340

Reputation:

Re-select and upload the same file

You cannot re-select and upload the same file except in Firefox, which mistakenly allows you to do so:

<input type="file" id="fileChooser">
document.getElementById('fileChooser').onchange = function () {
    alert('Uploaded!');
};

Here's my approach to resolve the issue. I wonder if there's a neater way to achieve it.

<input type="file" id="fileChooser">
var fileChooser = document.getElementById('fileChooser');
fileChooser.onclick = function () {
    this.value = '';
};
fileChooser.onchange = function () {
    if (this.value) {
        alert('Uploaded!');
    }
};

On JSFiddle: http://jsfiddle.net/scMF6/2/

Explanation:

You cannot re-select the same file twice in a row, i.e. you select and upload foo.txt on your desktop, for example, and then click the file chooser again, file select dialog appears and you try to select the same file again -- the browser simply does nothing and no alert box appears.

Upvotes: 15

Views: 6545

Answers (3)

Артем
Артем

Reputation: 31

Thanks for idea! If some one use GWT, then you can use this code)

     ...//some code :)
     Event.setEventListener(btn, new EventListener() {    
           @Override
           public void onBrowserEvent(Event event) {
           //work with IE11+ and other modern browsers
           nativeClearFile(fileUpload.getElement());
           //throw event click 
           InputElement.as(fileUpload.getElement()).click();
           }
          });
    Event.sinkEvents(btn, Event.ONCLICK);
    ...//continue code :)

    private native void nativeClearFile(Element element) /*-{
        element.value = '';
    }-*/;

Upvotes: 3

ShirAzi
ShirAzi

Reputation: 44

you must initialize "change event" after "click event":

 var fileChooser = document.getElementById('fileChooser');
    fileChooser.onclick = function () {
        this.value = '';
        fileChooser.onchange = function () {
            if (this.value) {
                alert('Uploaded!');
            }
        };
    };

Upvotes: 0

Sanjeev
Sanjeev

Reputation: 2667

Your solution has one problem, after selecting a file when you click it second time it clears the file input. Now if user does not select a new file and cancels Browse pop up then his old selection is gone.

This is not the default behavior of file input in FF.

I guess if you have some handle or callback for upload then you should clear your file input in that.

Upvotes: 0

Related Questions