【问题标题】:Clearing an HTML file upload field via JavaScript通过 JavaScript 清除 HTML 文件上传字段
【发布时间】:2010-10-24 04:40:20
【问题描述】:

当用户选择另一个选项时,我想重置文件上传字段。

这可以通过 JavaScript 实现吗?我怀疑文件上传元素的处理方式不同,因为它与用户的文件系统交互,并且可能是不可变的。

基本上,我想要的是(伪代码):

// Choose selecting existing file
$('#select-file').bind('focus', function() {
  // Clear any files currently selected in #upload-file
  $('#upload-file').val(''); 
}) ;

// Choose uploading new one - this works ok
$('#upload-file').bind('focus', function() {
  // Clear any files currently selected in #select-file
  $('#select-file').val(''); 
}) ;

注意:这个问题及其答案跨越了从 2009 年到今天。 浏览器和方法在那个时候发生了变化,请记住这一点来选择您的解决方案:)

【问题讨论】:

标签: javascript jquery html file-upload


【解决方案1】:

你不能在大多数浏览器中设置输入值,但你可以做的是创建一个新元素,从旧元素中复制属性,然后交换两者。

给定一个类似的形式:

<form> 
    <input id="fileInput" name="fileInput" type="file" /> 
</form>

直接的 DOM 方式:

function clearFileInput(id) 
{ 
    var oldInput = document.getElementById(id); 

    var newInput = document.createElement("input"); 

    newInput.type = "file"; 
    newInput.id = oldInput.id; 
    newInput.name = oldInput.name; 
    newInput.className = oldInput.className; 
    newInput.style.cssText = oldInput.style.cssText; 
    // TODO: copy any other relevant attributes 

    oldInput.parentNode.replaceChild(newInput, oldInput); 
}

clearFileInput("fileInput");

简单的 DOM 方式。这可能不适用于不喜欢文件输入的旧浏览器:

oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);

jQuery 方式:

$("#fileInput").replaceWith($("#fileInput").val('').clone(true));

// .val('') required for FF compatibility as per @nmit026

通过 jQuery 重置整个表单:https://stackoverflow.com/a/13351234/1091947

【讨论】:

  • 我尝试了上面其他两个建议的选项,这个链接上的示例代码是最终效果最好的一个。我真的希望 Udo 的回答能做到这一点,但事实并非如此。我也试过gusiev.com/2009/04/clear-upload-file-input-field谢谢克里斯H
  • 这是迄今为止我发现的最好的,但我仍然对附加到该字段的事件有疑问。不过谢谢!
  • 或使用 jQuery(在 change 事件处理程序内):$(this).replaceWith( $(this).clone(true) );
  • 您也可以将其包装成一个表单并使用 jQuery 重置它,如下所述:stackoverflow.com/a/13351234/1091947
  • $("#CV").replaceWith($("#CV").clone(true)); 在 Firefox 中不起作用,但在其他桌面浏览器中起作用(尚未测试 Safari)。 $("#CV").replaceWith($("#CV").val('').clone(true)); 似乎无处不在。
【解决方案2】:

现在只是在 2014 年,具有 id 的输入元素支持函数val('')

对于输入-

<input type="file" multiple="true" id="File1" name="choose-file" />

这个js清空输入元素-

$("#File1").val('');

【讨论】:

  • 这是否适用于所有浏览器,或者至少适用于四大浏览器的过去几个版本?我已经看到了一些在 FF 中有效但在 IE 中无效的问题。
  • 接受的答案对我不起作用,因为我使用 Angular 2,并且替换元素似乎不适用于 Angular。然而,这个解决方案确实有效——所以它得到了我的支持!
【解决方案3】:

简单的解决方案:

document.getElementById("upload-files").value = "";

【讨论】:

    【解决方案4】:

    是的,上传元素受到保护,不会在不同浏览器中被直接操作。但是,您可以从 DOM 树中删除元素,然后通过 JavaScript 在其位置插入一个新元素。这会给你同样的结果。

    类似的东西:

    $('#container-element').html('<input id="upload-file" type="file"/>');
    

    【讨论】:

    • 非常好 - 可以试一试,运行现有元素的副本应该很麻烦
    【解决方案5】:

    我最终使用的代码是,

    clearReviewFileSel: function() {
      var oldInput = document.getElementById('edit-file-upload-review-pdf') ;
      var newInput = document.createElement('input');
      newInput.id    = oldInput.id ;
      newInput.type  = oldInput.type ;
      newInput.name  = oldInput.name ;
      newInput.size  = oldInput.size ;
      newInput.class  = oldInput.class ;
      oldInput.parentNode.replaceChild(newInput, oldInput); 
    }
    

    感谢大家的建议和指点!

    【讨论】:

    • 感谢您发布代码!今晚你为我节省了时间和挫败感。
    • 在 IE8 中,“类”不是有效属性。它是“类名”。
    【解决方案6】:

    更短的version 非常适合我,如下所示:

    document.querySelector('#fileUpload').value = "";
    

    【讨论】:

      【解决方案7】:

      他们没有获得焦点事件,所以你必须使用这样的技巧:清除它的唯一方法是清除整个表单

      <script type="text/javascript">
          $(function() {
              $("#wrapper").bind("mouseover", function() {
                  $("form").get(0).reset();
              });
          });
      </script>
      
      <form>
      <div id="wrapper">
          <input type=file value="" />
      </div>
      </form>
      

      【讨论】:

      • 谢谢 - 是的,我还想知道是否有一种 UI 方法可以让用户在不重置整个表单的情况下清除自己的文件上传字段
      • @ChadGrant 好点,谢谢。我所做的只是用表单包装输入,重置表单,然后打开它:)
      【解决方案8】:

      真的很喜欢这样简单:)

      $('input[type=file]').wrap('<form></form>').parent().trigger('reset').children().unwrap('<form></form>');
      

      【讨论】:

        【解决方案9】:

        这个 jQuery 在 IE11、Chrome 53 和 Firefox 49 中为我工作:

        cloned = $("#fileInput").clone(true);
        cloned.val("");
        $("#fileInput").replaceWith(cloned);
        

        【讨论】:

          【解决方案10】:

          试试这个效果很好

          document.getElementById('fileUpload').parentNode.innerHTML = document.getElementById('fileUpload').parentNode.innerHTML;
          

          【讨论】:

            【解决方案11】:

            为了在 ajax 不可用时的兼容性,设置 .val('') 否则它将重新发送最后一个 ajax 上传的文件,该文件仍然存在于输入中。以下内容应在保留 .on() 事件的同时正确清除输入:

            var input = $("input[type='file']");
            input.html(input.html()).val('');
            

            【讨论】:

              【解决方案12】:

              试试这个代码...

              $("input[type=file]").wrap("<div id='fileWrapper'/>");
              $("#fileWrapper").append("<div id='duplicateFile'   style='display:none'>"+$("#fileWrapper").html()+"   </div>");
              $("#fileWrapper").html($("#duplicateFile").html());
              

              【讨论】:

                【解决方案13】:

                jQuery 测试方法在 FF 和 Chrome 中运行良好:

                $(function(){
                    $.clearUploadField = function(idsel){
                        $('#your-id input[name="'+idsel+'"]').val("") 
                    }
                });
                

                【讨论】:

                  【解决方案14】:

                  如果您有以下情况:

                  <input type="file" id="FileSelect">
                  

                  那就做吧:

                  $("#FileSelect").val('');
                  

                  重置或清除上次选择的文件。

                  【讨论】:

                    【解决方案15】:

                    我知道FormData api 对旧版浏览器等不太友好,但在许多情况下,无论如何你都在使用它(希望testing for support),所以它可以正常工作!

                    function clearFile(form) {
                      // make a copy of your form
                      var formData = new FormData(form);
                      // reset the form temporarily, your copy is safe!
                      form.reset();
                      for (var pair of formData.entries()) {
                        // if it's not the file, 
                        if (pair[0] != "uploadNameAttributeFromForm") {
                          // refill form value
                          form[pair[0]].value = pair[1];
                        }
                        
                      }
                      // make new copy for AJAX submission if you into that...
                      formData = new FormData(form);
                    }

                    【讨论】:

                      【解决方案16】:

                      只是另一个用于底池,但您实际上可以更改输入的类型。 如果将类型设置为文本,然后返回文件,则似乎重置了元素。

                      var myFileInput = document.getElementById('myfileinput');
                      myFileInput.type = "text";
                      myFileInput.type = "file";
                      

                      它会重置。 在 Google Chrome、Opera、Edge、IE 11 中测试

                      【讨论】:

                        【解决方案17】:

                        我遇到了 ng2-file-upload 的问题。如果您正在通过 ng2-file-upload 寻找有关 angular 的解决方案,请参阅以下代码

                        HTML:

                        &lt;input type="file" name="myfile" #activeFrameinputFile ng2FileSelect [uploader]="frameUploader" (change)="frameUploader.uploadAll()" /&gt;

                        组件

                        import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

                        @ViewChild('activeFrameinputFile')InputFrameVariable: ElementRef;

                        this.frameUploader.onSuccessItem = (item, response, status, headers) =&gt; { this.InputFrameVariable.nativeElement.value = ''; };

                        【讨论】:

                          【解决方案18】:

                          我知道它已经很老了,但是在浏览器中测试:

                          $0.value=null; // when $0 is the file upload element we talking about
                          

                          删除该值并允许我像以前一样重新选择相同的文件(意味着它有效!)

                          在Chrome 81、FF 76、Safari(iPad mini)、360浏览器、百度浏览器、QQ浏览器、安卓浏览器中测试。

                          说明:

                          根据我的观点,选择的文件可能超过 1,您最好不要将值设置为字符串 - 最终值位于 $0.files 中,可能大于 1。浏览器需要解析从“值”中选择的值,因此它是一个活动属性。根据我的理解,将其设置为 null 会导致浏览器将其解析为 $0.files 中的 [] 空列表(这就是发生的事情......)

                          【讨论】:

                            猜你喜欢
                            • 2019-04-10
                            • 1970-01-01
                            • 2013-12-31
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2011-01-17
                            • 1970-01-01
                            • 1970-01-01
                            相关资源
                            最近更新 更多