Javascript 输入 type="file" 上的取消事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34855400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:57:28  来源:igfitidea点击:

Cancel event on input type="file"

javascriptjqueryfile-upload

提问by GWR

I am working with a standard file input for uploads, and I am looking for a way to attach a function to an event when the user clicks/hits enter on the "cancel" button (or escapes out from) the choose file dialog.

我正在使用用于上传的标准文件输入,并且我正在寻找一种方法,当用户单击/点击“取消”按钮(或退出)选择文件对话框时,将函数附加到事件。

I can't find any events that work across all browsers and platforms consistently.

我找不到任何可以在所有浏览器和平台上一致运行的事件。

I've read the answers to this question: Capturing cancel event on input type=filebut they don't work, as the change event doesn't fire in most browsers on canceling out of the choose file dialog.

我已经阅读了这个问题的答案:Capturing cancel event on input type=file但它们不起作用,因为在大多数浏览器中取消选择文件对话框时不会触发更改事件。

I'm looking for a pure js solution, but open to jquery solutions as well.

我正在寻找纯 js 解决方案,但也对 jquery 解决方案持开放态度。

Anyone solve this problem successfully?

有人成功解决了这个问题吗?

采纳答案by Twisty

A bit of research indicates that there is no way to detect when Cancel is selected in the File Selection dialog window. You can use onchangeor onblurto check if files have been selected or if something has been added to the input value.

一些研究表明,无法检测何时在“文件选择”对话框窗口中选择了“取消”。您可以使用onchangeonblur检查是否已选择文件或是否已将某些内容添加到输入中value

This could look like: https://jsfiddle.net/Twisty/j18td9cs/

这可能看起来像:https: //jsfiddle.net/Twisty/j18td9cs/

HTML

HTML

<form>
  Select File:
  <input type="file" name="test1" id="testFile" />
  <button type="reset" id="pseudoCancel">
    Cancel
  </button>
</form>

JavaScript

JavaScript

var inputElement = document.getElementById("testFile");
var cancelButton = document.getElementById("pseudoCancel");
var numFiles = 0;

inputElement.onclick = function(event) {
  var target = event.target || event.srcElement;
  console.log(target, "clicked.");
  console.log(event);
  if (target.value.length == 0) {
    console.log("Suspect Cancel was hit, no files selected.");
    cancelButton.onclick();
  } else {
    console.log("File selected: ", target.value);
    numFiles = target.files.length;
  }
}

inputElement.onchange = function(event) {
  var target = event.target || event.srcElement;
  console.log(target, "changed.");
  console.log(event);
  if (target.value.length == 0) {
    console.log("Suspect Cancel was hit, no files selected.");
    if (numFiles == target.files.length) {
      cancelButton.onclick();
    }
  } else {
    console.log("File selected: ", target.value);
    numFiles = target.files.length;
  }
}

inputElement.onblur = function(event) {
  var target = event.target || event.srcElement;
  console.log(target, "changed.");
  console.log(event);
  if (target.value.length == 0) {
    console.log("Suspect Cancel was hit, no files selected.");
    if (numFiles == target.files.length) {
      cancelButton.onclick();
    }
  } else {
    console.log("File selected: ", target.value);
    numFiles = target.files.length;
  }
}


cancelButton.onclick = function(event) {
  console.log("Pseudo Cancel button clicked.");
}

I suggest making your own cancel or reset button that resets the form or clears the value from the input.

我建议您制作自己的取消或重置按钮,以重置表单或清除输入中的值。

回答by DJones

I had the problem where I clicked the cancel button on the input type="file" element and wanted the function to do nothing. if something was selected and I clicked the open button then I wanted my function to do something. The example only shows the method, I stripped out what I do with it after it opens. I put in the alerts just so you could see there isn't a filename coming back from the dialog when cancel is clicked. Here is a method I use, it is simple but it works.

我在单击 input type="file" 元素上的取消按钮时遇到了问题,但希望该函数不执行任何操作。如果选择了某些内容并且我单击了打开按钮,那么我希望我的函数执行某些操作。这个例子只展示了方法,我在它打开后去掉了我用它做什么。我输入警报只是为了让您可以看到单击取消时没有从对话框返回的文件名。这是我使用的一种方法,它很简单,但很有效。

 function openFileOnClick(){
    document.getElementById("fileSelector").value = "";
    document.getElementById("fileSelector").files.length = 0;            
    document.getElementById("fileSelector").click();
    if(document.getElementById("fileSelector").files.length >= 1){
        alert(document.getElementById("fileSelector").value);
        //Do something 
    }
    else{
        alert(document.getElementById("fileSelector").value);
        //Cancel button has been called.
    }
}
<html>
<head>
</head>
<body>
<input type="file" id="fileSelector" name="fileSelector" value="" style="display:none;"  />
<input type="button" value="Open File" name="openFile" onclick="openFileOnClick();" />
</body>
</html>

回答by Anshika Srivastava

When we select the file following events are called -

当我们选择文件时,会调用以下事件 -

Scenario 1 :When the select file is clicked and then cancel is clicked

场景一:点击选择文件后点击取消

Focusevent value=""

Focus事件值=""

Clickevent value=""

Click事件值=""

Blurevent value=""

Blur事件值=""

Focusevent value=""

Focus事件值=""

Blur event value="" (when the user clicks somewhere out)

Blur event value=""(当用户点击某处时)

Scenario 2 :When the file is selected -

场景 2:选择文件时 -

Focusevent value=""

Focus事件值=""

Clickevent value=""

Click事件值=""

Blurevent value=""

Blur事件值=""

Focusevent value=""

Focus事件值=""

Changeevent value="filevalue"

Change事件值=“文件值”

Blurevent value="filevalue"

Blur事件值=“文件值”

Focusevent value="filevalue"

Focus事件值=“文件值”

Blur event value="filevalue" (when the user clicks somewhere out)

Blur event value="filevalue"(当用户点击某处时)

We see here, when the Blur event (last event) is called after focus event with no value of file means that the Cancel button is clicked.

我们在这里看到,在没有文件值的焦点事件之后调用 Blur 事件(最后一个事件)时,意味着单击了取消按钮。

My scenario was to change the Submit button text to "Please wait" while the file is loading currentEventvariable is used to hold the current event value either click or focus if the currentEvent = focus and file value is null means Cancel button is clicked.

我的方案是在文件加载时将提交按钮文本更改为“请稍候” currentEvent变量用于保存当前事件值,如果 currentEvent = focus 并且文件值为 null 则表示单击取消按钮。

Javascript

var currentEvent = "focus";

function onFileBrowse() {    
    var vtbFile = $('#uploadFile')[0].files[0];

    if (vtbFile != undefined) {
        var extension = vtbFile.name.split('.').pop().toLowerCase();
        var valError = "";

        if (extension === 'xlsx' || extension === 'xlsb' || extension === 'csv') {
            if (vtbFile.size === 0)
                valError = "File '" + vtbFile.name + "' is empty";
        }
        else
            valError = "Extension '" + extension + "' is not supported.";

        if (valError !== "") {            
            alert("There was an issue validating the file. " + valError, 20000);
        }        
    }
    //hide Indicator
    var buttonUpload = document.getElementById('btnUploadTB');
    buttonUpload.innerText = "Submit";
};


function fileClick() {
    //show Indicator
    var buttonUpload = document.getElementById('btnUploadTB');
    buttonUpload.innerText = "Please wait..";
    
    document.getElementById('uploadFile').value = null;   
    currentEvent = "click";
}
function fileFocus() {
    currentEvent = "focus";
}

function fileBlur() {
    
    if (!document.getElementById('uploadFile').value && currentEvent == "focus") {
        console.log('blur' + 'change to submit');
        //hide Indicator
        var buttonUpload = document.getElementById('btnUploadTB');
        buttonUpload.innerText = "Submit";
    }
}
HTML

<input class="k-button k-upload-button" type="file" id="uploadFile" name="uploadFile"
    accept=".csv,.xlsx,.xlsb" onChange='onFileBrowse()' onclick="fileClick()" onfocus="fileFocus()" onblur="fileBlur()" />

<button id="btnUploadTB" type="button" class="btn btn-default" onclick="uploadTBFile()" style="width:28%;margin-left: 3px;">Submit</button>