Clearing an HTML file upload field via JavaScript

JavascriptJqueryHtmlFile Upload

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

Simple solution:

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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!

Solution 6 - Javascript

Shorter version that works perfect for me that is as follow:

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

Solution 7 - Javascript

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>

Solution 8 - Javascript

really like keep things simple like this :)

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

Solution 9 - Javascript

This jQuery worked for me in IE11, Chrome 53, and Firefox 49:

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

Solution 10 - Javascript

try this its work fine

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

jQuery tested method working fine in FF & Chrome:

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

Solution 14 - Javascript

If you have the following:

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

then just do:

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

to reset or clear last selected file.

Solution 15 - Javascript

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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 = ''; };

Solution 18 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris BurgessView Question on Stackoverflow
Solution 1 - JavascriptChris HynesView Answer on Stackoverflow
Solution 2 - JavascriptPradyut BhattacharyaView Answer on Stackoverflow
Solution 3 - JavascriptOlegView Answer on Stackoverflow
Solution 4 - JavascriptUdoView Answer on Stackoverflow
Solution 5 - JavascriptChris BurgessView Answer on Stackoverflow
Solution 6 - JavascriptFrank WaalkensView Answer on Stackoverflow
Solution 7 - JavascriptChad GrantView Answer on Stackoverflow
Solution 8 - Javascriptdmi3yView Answer on Stackoverflow
Solution 9 - JavascriptChanakaView Answer on Stackoverflow
Solution 10 - JavascriptRissaView Answer on Stackoverflow
Solution 11 - JavascriptaberdatView Answer on Stackoverflow
Solution 12 - JavascriptNirajView Answer on Stackoverflow
Solution 13 - Javascriptcrisupisu emilView Answer on Stackoverflow
Solution 14 - JavascriptMuhammad AwaisView Answer on Stackoverflow
Solution 15 - JavascriptAbraham LabkovskyView Answer on Stackoverflow
Solution 16 - JavascriptAdam WhateversonView Answer on Stackoverflow
Solution 17 - JavascriptJavascriptsoldierView Answer on Stackoverflow
Solution 18 - JavascriptXerixView Answer on Stackoverflow