简体   繁体   English

通过 JavaScript 清除 HTML 文件上传字段

[英]Clearing an HTML file upload field via JavaScript

I want to reset a file upload field when the user selects another option.当用户选择另一个选项时,我想重置文件上传字段。

Is this possible via JavaScript?这可以通过 JavaScript 实现吗? I'm suspecting that the file upload element is treated differently because it interacts with the user's file system, and maybe it's immutable.我怀疑文件上传元素被区别对待,因为它与用户的文件系统交互,而且它可能是不可变的。

Basically, what I want is something like (pseudo-code):基本上,我想要的是(伪代码):

// 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(''); 
}) ;

NB: This question and its answers span the period from 2009 to today.注意:这个问题及其答案涵盖了从 2009 年到今天的时期。 Browsers and approaches have changed in that time, please select your solutions with this in mind :)那个时候浏览器和方法发生了变化,请考虑到这一点来选择您的解决方案:)

You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.您不能在大多数浏览器中设置输入值,但您可以做的是创建一个新元素,从旧元素复制属性,然后交换两者。

Given a form like:给定一个形式,如:

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

The straight DOM way:直接的 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");

Simple DOM way.简单的 DOM 方式。 This may not work in older browsers that don't like file inputs:这在不喜欢文件输入的旧浏览器中可能不起作用:

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

The jQuery way: jQuery方式:

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

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

Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947通过 jQuery 重置整个表单: https : //stackoverflow.com/a/13351234/1091947

Simply now in 2014 the input element having an id supports the function val('') .只是现在在 2014 年,具有 id 的输入元素支持函数val('')

For the input -对于输入 -

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

This js clears the input element -这个js清除了输入元素 -

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

简单的解决方案:

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

Yes, the upload element is protected from direct manipulation in different browsers.是的,上传元素受到保护,不会在不同浏览器中直接操作。 However, you could erase the element from the DOM tree and then insert a new one in its place via JavaScript.但是,您可以从 DOM 树中删除该元素,然后通过 JavaScript 在其位置插入一个新元素。 That would give you the same result.那会给你同样的结果。

Something along the lines of:类似的东西:

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

The code I ended up using was,我最终使用的代码是,

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); 
}

Thanks everyone for the suggestions and pointers!谢谢大家的建议和指点!

更适合我的较短version如下:

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

真的很喜欢像这样保持简单:)

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

They don't get focus events, so you'll have to use a trick like this: only way to clear it is to clear the entire form他们没有获得焦点事件,因此您必须使用这样的技巧:清除它的唯一方法是清除整个表单

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

<form>
<div id="wrapper">
    <input type=file value="" />
</div>
</form>

This jQuery worked for me in IE11, Chrome 53, and Firefox 49:这个 jQuery 在 IE11、Chrome 53 和 Firefox 49 中对我有用:

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

试试这个它工作正常

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

For compatibility when ajax is not available, set .val('') or it will resend the last ajax-uploaded file that is still present in the input.为了在 ajax 不可用时的兼容性,设置 .val('') 否则它将重新发送仍然存在于输入中的最后一个 ajax 上传的文件。 The following should properly clear the input whilst retaining .on() events:以下应正确清除输入,同时保留 .on() 事件:

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

jQuery tested method working fine in FF & Chrome: jQuery 测试方法在 FF 和 Chrome 中工作正常:

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

If you have the following:如果您有以下情况:

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

then just do:然后就做:

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

to reset or clear last selected file.重置或清除上次选择的文件。

I know the FormData api is not so friendly for older browsers and such, but in many cases you are anyways using it (and hopefully testing for support ) so this will work fine!我知道FormData api 对旧浏览器等不太友好,但在许多情况下,您无论如何都在使用它(并希望测试支持)所以这会正常工作!

 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); }

Just another one for the pot but you can actually change the type of an input.只是另一个锅,但您实际上可以更改输入的类型。 If you set the type to text, then back to file, it seems to reset the element.如果您将类型设置为文本,然后返回到文件,它似乎重置了元素。

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

It resets.它重置。 Tested in Google Chrome, Opera, Edge, IE 11在 Google Chrome、Opera、Edge、IE 11 中测试

Try this code...试试这个代码...

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

I faced the issue with ng2-file-upload for angular.我遇到了 ng2-file-upload for angular 的问题。 if you are looking for the solution on angular by ng2-file-upload, refer below code如果您正在通过 ng2-file-upload 寻找有关 angular 的解决方案,请参阅以下代码

HTML: HTML:

<input type="file" name="myfile" #activeFrameinputFile ng2FileSelect [uploader]="frameUploader" (change)="frameUploader.uploadAll()" /> <input type="file" name="myfile" #activeFrameinputFile ng2FileSelect [uploader]="frameUploader" (change)="frameUploader.uploadAll()" />

component成分

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

@ViewChild(' activeFrameinputFile ') InputFrameVariable : ElementRef; @ViewChild(' activeFrameinputFile ') InputFrameVariable : ElementRef;

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

I know it is quite old, but testing in the browser:我知道它很旧,但在浏览器中测试:

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

erased the value and allow me to rechoose THE SAME FILE as before (means it worked!)删除了值并允许我像以前一样重新选择相同的文件(意味着它起作用了!)

Tested in Chrome 81, FF 76, Safari (on iPad mini), 360 browser, Baidu browser, QQ browser, android browser.在 Chrome 81、FF 76、Safari(在 iPad mini 上)、360 浏览器、百度浏览器、QQ 浏览器、android 浏览器中测试。

Explanation:解释:

As per my point of view that files selected can be more than 1, you'd better not set the value to a string - the final value sits in $0.files which may be more than 1. The browser need to parse the selected values from "value", so it is an active property.根据我的观点,选择的文件可以大于 1,您最好不要将该值设置为字符串 - 最终值位于 $0.files 中,可能大于 1。浏览器需要解析所选值来自“价值”,所以它是一个主动属性。 Set it to null, as per my understanding, will cause the browser to parse it to [] empty list in $0.files (this is what happened...)根据我的理解,将其设置为 null 将导致浏览器将其解析为 $0.files 中的 [] 空列表(这就是发生的事情......)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM