244
votes

Is there any chance to detect every file selection the user made for an HTML input of type file element?

This was asked many times before, but the usually proposed onchange event doesn't fire if the user select the same file again.

8
Would your code then also have to fire if the user hits Cancel then? One expects that hitting Cancel will do nothing, and I think most users would further expect that re-selecting the same file would have the same effect as Cancel. I don't know if this is possible or not but I suggest you reconsider this design anyway.KRyan
On cancel it should not fire or make it otherwise detectable. It is more meant to remove an UI ceveat: If some action is invoked after the file is choosen, the user usually expect the action to repeat if he choose the file again.dronus
Maybe we can have this behaviour if we set the inputs value to '' after doing something with the file. But that would remove the visible filename too. However, that may be ok, as the file is actually processed and the result of that action may appear somewhere else.dronus
Plz Explain the Que What you want to do?Champ
All I want is to simulate the old school behaviour desktop applications have. If I 'open' the same file again in an desktop application, it is usually reloaded, or if some action is done with the file (like converting it so another format for example) this action is done again. This is what desktop users may expect from a web app too, but the file input onchange event doesn't resemble.dronus

8 Answers

330
votes

Set the value of the input to null on each onclick event. This will reset the input's value and trigger the onchange event even if the same path is selected.

var input = document.getElementsByTagName('input')[0];

input.onclick = function () {
  this.value = null;
};
  
input.onchange = function () {
  console.log(this.value);
};
<input type="file" value="C:\fakepath">

Note: It's normal if your file is prefixed with 'C:\fakepath'. That's a security feature preventing JavaScript from knowing the file's absolute path. The browser still knows it internally.

25
votes
<form enctype='multipart/form-data'>
    <input onchange="alert(this.value); this.value=null; return false;" type='file'>
    <br>
    <input type='submit' value='Upload'>
</form>

this.value=null; is only necessary for Chrome, Firefox will work fine just with return false;

Here is a FIDDLE

25
votes

Use onClick event to clear value of target input, each time user clicks on field. This ensures that the onChange event will be triggered for the same file as well. Worked for me :)

onInputClick = (event) => {
    event.target.value = ''
}

<input type="file" onChange={onFileChanged} onClick={onInputClick} />

Using TypeScript

onInputClick = ( event: React.MouseEvent<HTMLInputElement, MouseEvent>) => {
    const element = event.target as HTMLInputElement
    element.value = ''
}
8
votes

In this article, under the title "Using form input for selecting"

http://www.html5rocks.com/en/tutorials/file/dndfiles/

<input type="file" id="files" name="files[]" multiple />

<script>
function handleFileSelect(evt) {

    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
     // Code to execute for every file selected
    }
    // Code to execute after that

}

document.getElementById('files').addEventListener('change', 
                                                  handleFileSelect, 
                                                  false);
</script>

It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.

6
votes
handleChange({target}) {
    const files = target.files
    target.value = ''
}
1
votes

Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm

   $('#myFile').change(function () {
       LoadFile("myFile");//function to do processing of file.
       $('#myFile').val('');// set the value to empty of myfile control.
    });
1
votes

Clearing the value of 0th index of input worked for me. Please try the below code, hope this will work (AngularJs).

          scope.onClick = function() {
            input[0].value = "";
                input.click();
            };
0
votes

Usage of two way binding worked for me if you are working with Angular.

Here is my HMTL

<input type="file" #upload name="upload" [(ngModel)]="inputValue"(change)='fileEvent($event)'/>

and TS..

  @ViewChild('upload') uploadBtn: HTMLElement;

  fileEvent(e: any){
    
   //file upload part... 

    this.inputValue = "";
  }