“On file dialog cancel” event in JavaScript

后端 未结 2 1880
野趣味
野趣味 2021-01-17 16:01

I have a file input:


Function \'foo\' is called only when user chooses some f

相关标签:
2条回答
  • 2021-01-17 16:42

    I think that the best way if you can change a bit your code, is adding plugins to add files, for example:

    http://swfupload.org/

    or

    http://www.uploadify.com

    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

    0 讨论(0)
  • 2021-01-17 16:43

    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.

    0 讨论(0)
提交回复
热议问题