Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"On file dialog cancel" event in JavaScript

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.

like image 322
r5ha Avatar asked May 04 '26 19:05

r5ha


1 Answers

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.')}
)
like image 98
MSS Avatar answered May 06 '26 10:05

MSS