如何识别用户未选择文件而关闭的HTML文件上传向导

how to identify html file upload wizard closed by user without selecting file

本文关键字:文件 HTML 向导 选择 何识别 识别 用户      更新时间:2023-09-26

我需要确定用户是否关闭了浏览器的文件上传向导而没有选择文件。应该在关闭向导后立即进行识别,并且必须能够使用JavaScript完成识别。当用户关闭文件选择向导进行上传时,是否会触发任何事件?我们也可以使用JQuery。我使用了几个事件,但没有一个在向导关闭后立即触发。

<input type="file" id="fileTaker" 
               oncancel="cancelledFile()"
               onabort="abortedFile()"
               onclose="closedFile()"
               onclick="clickedFile()"
               onchange="changedFile()"
               onblur="bluredFile()"
               onemptied="emptiedFile()"
               onformchange="formChanged()"
               onsuspend="suspendFile()"
               />

这里onchange仅在用户选择文件并打开上传时触发(onchange在向导关闭后偶尔触发)。但我需要可靠的事件)。打开向导时会触发Onclick和onblur。其他人没有被解雇。谢谢你。

可以在<input type="file">元素上使用changeblur事件,在window元素上使用focus事件;检查<input type="file">元素.files属性.length是否等于0

<script>
  function changedFile(el, fromfocus) {
    // remove `fromfocus` to set condition
    // to `true` for both `onchange` event 
    // and direct call to `changedFile`
    // from within `window.onfocus` handler
    if (el.files.length === 0 && fromfocus) {
      console.log(el.files.length);
    }
  }
  
  function handleBlur(el) {
    window.onfocus = function() {
      this.onfocus = null;
      // pass `true` to prevent `if` statement 
      // being `true` for both `onchange` event
      // and direct call to `changedFile` here
      changedFile(el, true);
    }
  }
</script>
<input type="file" id="fileTaker" 
       onchange="changedFile(this)" 
       onblur="handleBlur(this)" />