Image by 200 Degrees from Pixabay

TIL how to reset a HTML input file

When you want to upload a file, you often want to see a preview before sending it. To do this, I show a preview in a canvas. But even if I close the preview part, the input is still loaded with the selected filed. So, if you try to show again the preview of the same file, no event is catched in the onChange method.

I found a solution to do this with a single line of code.

To reset a HTML input file :

<input id="fileuploader" type="file" onChange={(event)=> handleFileUpdate(event)}/>

It can be easily done by replacing its value by an empty string :

document.getElementById("fileuploader").value = "";

This way, if you try to upload again the same file, becuase the value has changed, the onChange event is catched and you can preview it again.

Hope it helps!

 

Enjoy!