简体   繁体   中英

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? 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. 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:

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. This may not work in older browsers that don't like file inputs:

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

The jQuery way:

$("#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

Simply now in 2014 the input element having an id supports the function val('') .

For the input -

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

This js clears the input element -

$("#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. 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:

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. The following should properly clear the input whilst retaining .on() events:

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

jQuery tested method working fine in 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!

 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

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. if you are looking for the solution on angular by ng2-file-upload, refer below code

HTML:

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

this.frameUploader.onSuccessItem = (item, response, status, headers) => { this. 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.

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. 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...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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