To handle file uploads on a website we have to use a hidden <input type="file" />
element.
To find out what file has been selected in the Select File Dialog, we can use the onchange
event.
But how can we detect if the user has hit the cancel button?
Unfortunately, there is no oncancel
event.
There exist a lot of workarounds to detect if the user has hit the cancel button, but due to the problem I described here, none of them worked for me reliably.
There is a file input cancel event that can be used.
HTML
<label for="file">Select or file. Or don't.</label>
<input type="file" id="file" name="file" />
<div id="result"></div>
Javascript
const elem = document.getElementById("file");
const result = document.getElementById("result");
elem.addEventListener("cancel", () => {
result.textContent = "Canceled.";
});`
More details in the documenation