Reputation: 342
I have a file input:
<input type=file id=file onchange='foo(this.files)'/>
Function 'foo' is called only when user chooses some file in the file upload dialog and clicks "OK". Is there any event that will be fired when user clicks "cancel" button in the dialog? HTML5-only solutions are OK.
Upvotes: 10
Views: 4429
Reputation: 3860
There is a new cancel event for dialogs that it works for file dialog too. I wrote a file to open file and read it, you can use cancel part:
function openFile(callback,onCancel) {
var el = document.createElement('input');
el.setAttribute('type', 'file');
el.style.display = 'none';
document.body.appendChild(el);
el.onchange = function () {
const reader = new FileReader();
reader.onload = function () {
callback(reader.result);
document.body.removeChild(el);
};
reader.readAsBinaryString(el.files[0]);
}
el.oncancel=(event) => {
if(onCancel){
onCancel(event);
}
};
el.click();
}
Use example:
openFile(
(data)=>{alert('file has been read successfully.')},
()=>{alert('user canceled operation.')}
)
Upvotes: 2
Reputation: 11809
There's no event (only fires the change/input
event if you have one file already selected when you click on it, because it changes to zero selected items) so this don't really answer your question. Right now the only thing I can think of is to take advantage of dialogs that open when you click the button.
The current behavior (as I checked in Chrome) is to lose the window focus when the input is clicked and the dialog is shown, and is impossible to get again the focus on the window because when you try to do so, you get the focus on the dialog. To get the focus on the window you need to close the dialog by force. With all this we can hack something like this:
const input = document.getElementById('inp');
let timeout = null;
let dialogopen = false;
function checkFiles() {
dialogopen = false;
console.log("File count:", input.files.length);
}
input.addEventListener('change', (event) => {
clearTimeout(timeout);
checkFiles();
});
input.addEventListener('click', (event) => {
clearTimeout(timeout);
dialogopen = true;
});
window.addEventListener('focus', (event) => {
if (dialogopen) {
clearTimeout(timeout);
timeout = setTimeout(checkFiles, 100);
}
});
Click me: <input type="file" id="inp" />
Maybe this helps someone in the future.
Upvotes: 1
Reputation: 2894
I think that the best way if you can change a bit your code, is adding plugins to add files, for example:
or
these are the more common, I'd work with the first and I had no problems.
This will not do exactly what you want, but you can add files in a queue and then cancel them, and you can capture this event...
I know that is not what you was looking for, but is the best solution I can give you
good luck! I hope I've helped you
Upvotes: -2