Javascript 使用带有 .change() 事件的 input type="file" 字段上传文件并不总是在 IE 和 Chrome 中触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10214947/
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-24 00:20:52  来源:igfitidea点击:

Upload files using input type="file" field with .change() event not always firing in IE and Chrome

javascriptjqueryinternet-explorerfirefoxgoogle-chrome

提问by jwaliszko

I have simple piece of code to upload files:

我有一段简单的代码来上传文件:

$(document).ready(function () {
    $(".attachmentsUpload input.file").change(function () {
        $('form').submit();
    });
});

<form class="attachmentsUpload" action="/UploadHandler.ashx" method="post" enctype="multipart/form-data">
    <input type="file" class="file" name="file" />
</form>

While I click on input and then select a file in dialog box, I'm submitting this file using ajax. This is not important part here. Important part is, that while I select the same file second time in the dialog box, just after submitting the first file, the .change() event does not fire in IE and Chrome. But while I choose different file, the event fires and works properly. Under Firefox it is firing all the time.

当我单击输入然后在对话框中选择一个文件时,我正在使用 ajax 提交这个文件。这不是这里的重要部分。重要的部分是,当我在对话框中第二次选择同一个文件时,在提交第一个文件后, .change() 事件不会在 IE 和 Chrome 中触发。但是当我选择不同的文件时,事件会触发并正常工作。在 Firefox 下,它一直在发射。

How to workaround this, to work as expected (as in Firefox) ?

如何解决这个问题,按预期工作(如在 Firefox 中)?

回答by dknaack

Description

描述

This happens because the value of the input field (the selected filepath) does not change if you select the same file again.

发生这种情况是因为如果您再次选择相同的文件,输入字段(选定的文件路径)的值不会更改。

You can set the value in the onChange()event to an empty string and submit your form only if the value is not empty. Have a look at my sample and this jsFiddle Demonstration.

您可以将onChange()事件中的值设置为空字符串,并仅在该值不为空时提交表单。看看我的示例和这个jsFiddle Demonstration

Sample

样本

$(".attachmentsUpload input.file").change(function () {
    if ($(".attachmentsUpload input.file").val() == "") {
        return;
    }
    // your ajax submit
    $(".attachmentsUpload input.file").val("");
});

Update

更新

This, for any reason, does not work in IE9. You can replace the element to reset them. In this case you need jQuery live()to bind the event, because your input field will dynamically (re)created.This will work in all browsers.

出于任何原因,这在 IE9 中不起作用。您可以替换元素以重置它们。 在这种情况下,您需要 jQuerylive()来绑定事件,因为您的输入字段将动态(重新)创建。这将适用于所有浏览器。

I found this solution on the stackoverflow answer Clearing input type='file' using jQuery

我在 stackoverflow 答案Clearing input type='file' using jQuery上找到了这个解决方案

$(".attachmentsUpload input.file").live("change", function () {
    if ($(".attachmentsUpload input.file").val() == "") {
        return;
    }
    // get the inputs value
    var fileInputContent = $(".attachmentsUpload input.file").val();
    // your ajax submit
    alert("submit value of the file input field=" + fileInputContent);
    // reset the field
    $(".attachmentsUpload input.file").replaceWith('<input type="file" class="file" name="file" />');
});?

More Information

更多信息

Check out my updated jsFiddle

查看我更新的jsFiddle

Note:liveis now removedfrom later versions of jQuery. Please use oninstead of live.

注意:live现在从更高版本的 jQuery 中删除。请使用on代替live

回答by jwaliszko

Based on dknaack answer, the clue is usage of jquery live to bind change event and resetting the input field after submit:

基于 dknaack 的回答,线索是使用 jquery live 绑定更改事件并在提交后重置输入字段

$(document).ready(function () {
    $(".attachmentsUpload input.file").change(function () {
        $('form').submit();  /* sync submit */
        $(".attachmentsUpload input.file").replaceWith('<input type="file" class="file" name="file" />');
    });
});

The resetting must be performed after submitevent is done. When the submit is async, reset the field for example in ajax successevent.

必须在提交事件完成进行重置。当提交是async 时,例如在ajax 成功事件中重置该字段。

$(document).ready(function () {
    $(".attachmentsUpload input.file").change(function () {
        $('form').submit();  /* async submit */
    });
});

.ajaxForm({
    ...
    success: function (result) {
        // reset the field - needed for IE to upload the same file second time                    
        $this.find("input.file").replaceWith('<input type="file" class="file" name="file" />');
    }
});