11

I am using infile to ask the users to browse for a file on their machine. Is there way to catch if the window is closed without file being selected?
For example if x is clicked.

<input type="file" name="data" id="inFile" size="15" style="display:none" onchange="handleFiles(this)"/>

Thanks

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
setlio
  • 726
  • 2
  • 13
  • 32

3 Answers3

2

With the solution from HTML input file selection event not firing upon selecting the same file, I think you can use this:

<input type="file" name="data" id="inFile" />
var fileElem = document.getElementById("inFile");
var fileSelected = null;
fileElem.onclick = function(e) {
    fileSelected = this.value;
    this.value = null;
});
/* or use this in your browse() function:
    fileElem.value = null;
*/
fileElem.onchange = function(e) { // will trigger each time
    handleFileDialog(this.value === fileSelected);
};

function handleFileDialog(changed) {
    // boolean parameter if the value has changed (new select) or not (canceled)
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

What I did is: Start timer after the user opens the window, and in that timed function I check every 0.5 sec if the file has been selected with boolean var. I stop the timer as soon as user selects the file or HTML5 DnD occurs. I hope this helps someone.

<div id="uploader"><input type="file" name="data" id="inFile" size="15" style="display:none" onchange="handleFiles(this)"/></div>

<button dojoType="dijit.form.Button" id="fileSelect" type="button" onmouseup="browse();">Browse</button> 

var fileselected = false;
function handleFiles(input){
    fileselected = true;
//use input
}

var interval;
function browse(){
    fileselected = false;
    var fileElem = document.getElementById("inFile");
    fileElem.click();
    interval = setInterval(setdiv, 500);

}
function setdiv(){
    if(!fileselected){  
        //do staff until user decides to Dnd or  browse for file again
        clearInterval(interval);
    }   
}
malix
  • 3,566
  • 1
  • 31
  • 41
setlio
  • 726
  • 2
  • 13
  • 32
  • 1
    How does it help to catch event of closing dialog on cancelling? You timer will run forever if user clicks "Cancel" :-( – Philipp Munin Jan 12 '18 at 11:47
-3

I think the blur event will do it:

<input
  type="file"
  onchange="changed=true; handleFiles(this)"
  onblur="if(!changed) alert('nothing selected'); changed=false;"
/>
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Hm, I fear this is the first event that comes when abort the selection - I see no other way. – Bergi Aug 22 '12 at 22:41
  • I came here, because i just wanted highlight div under hidden fileinput when it is selected, so, use of onfocus and onblur was right solution in my case. – Andrei Nov 24 '16 at 16:51