459

I am developing a metro app with VS2012 and Javascript

I want to reset the contents of my file input:

<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />

How should I do that?

Mosh Feu
  • 24,625
  • 12
  • 74
  • 111
Jesus
  • 7,426
  • 4
  • 24
  • 38
  • 1
    What do you mean by content? – Maess Dec 12 '13 at 16:48
  • 4
    do you mean, after the user selects a file, you want to reset the selected file to "nothing"? – ddavison Dec 12 '13 at 16:49
  • 9
    Possible duplicate of http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery – Dhaval Marthak Dec 12 '13 at 16:52
  • 1
    Yes, the path on my input type= file how to clear that what's the magic word :p – Jesus Dec 12 '13 at 16:58
  • @Dhaval Marthak: yes it works but I was looking a solution either with pure Javascript or WinJS so far I implemented your solution with jQuery and it Worked – Jesus Dec 12 '13 at 17:55
  • 16
    it [seems](http://jsfiddle.net/kojk65rv/) that a simple `inputElement.value = ""` does the trick just fine without resorting to cloning or wrapping as suggested. Works in CH(46), IE(11) and FF(41) – Robert Koritnik Oct 23 '15 at 21:37
  • 4
    Possible duplicate of [How can I clear an HTML file input with JavaScript?](http://stackoverflow.com/questions/1703228/how-can-i-clear-an-html-file-input-with-javascript) – Frank Tan Sep 26 '16 at 17:58
  • I found a answer that workds for me in another topic : http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery – Mickaël Lalande Apr 03 '17 at 20:46
  • Possible duplicate of [How to clear File Input](https://stackoverflow.com/questions/9617738/how-to-clear-file-input) – GeekyCoder Aug 21 '19 at 07:11

28 Answers28

442

The jQuery solution that @dhaval-marthak posted in the comments obviously works, but if you look at the actual jQuery call it's pretty easy to see what jQuery is doing, just setting the value attribute to an empty string. So in "pure" JavaScript it would be:

document.getElementById("uploadCaptureInputFile").value = "";
Jordan Kasper
  • 12,144
  • 3
  • 33
  • 52
  • 17
    Thanks! If you already have the jquery reference anyway, $input.val("") will work as usual. – Natan Mar 01 '14 at 13:57
  • @2ndGAB Hmm... I only have 45.0.1 so I can't test... anyone else? – Jordan Kasper May 05 '16 at 19:08
  • @2ndGAB Correction, My Firefox just updated to 46.0.1 and this code still works there. Can you confirm? – Jordan Kasper May 05 '16 at 19:09
  • @jakerella that's strange, for me, set an input file selector value trigs a Security exception. The only solution I successfully use is `$(#myfileselector).trigger('fileselect', [1, ""]);` – fralbo May 09 '16 at 07:48
  • This is the best answer. Thank you! – WebBrother Sep 21 '16 at 09:25
  • Weirdly, this works, but setting the value to `undefined` or deleting it does not. `null` works, but I don't know if that's better than `''`. – trysis Jan 10 '17 at 19:26
  • 5
    input.type = ''; input.type = 'file'; //enjoy – Maxmaxmaximus Feb 02 '17 at 11:59
  • @Maxmaxmaximus This will not work across browsers. I just tried in Safari and setting the `type` to blank string changed the "file" field to a blank text field, but then setting the `type` back to "file" did not work (it stayed a text field). This is a [security restriction some browsers still have](http://stackoverflow.com/questions/1544317/change-type-of-input-field-with-jquery). However, setting the `value` to an empty string did still work. – Jordan Kasper Feb 02 '17 at 14:14
  • This answer is not good enough. If the input is set as `required`, resetting the field should make the field invalid again. Unfortunately in this case, it is still valid, so the form will submit, although with no value. – pepkin88 Apr 24 '19 at 16:48
  • jQuery was not requested and should not be given as answer unless absolutely necessary. – CodeFinity May 26 '19 at 22:37
89

You need to wrap <input type = “file”> in to <form> tags and then you can reset input by resetting your form:

onClick="this.form.reset()"
levkaster
  • 2,404
  • 1
  • 22
  • 30
  • 7
    This is the correct method. It works in all browsers and does not conflict with any protections that browsers implement to prevent rogue scripts from messing around with file input's .value. – Eugene Ryabtsev Mar 21 '16 at 08:26
  • 13
    Kinda cool, not for me though, cause it also resets other fields on this form. – Starwave Dec 05 '17 at 09:54
  • 2
    A similar jQuery solution could be `$("form").get(0).reset();`. The `.get(0)` will return the actual form element so you can use the `reset()` function. – teewuane Mar 16 '18 at 16:16
77

This is the BEST solution:

input.value = ''

if(!/safari/i.test(navigator.userAgent)){
  input.type = ''
  input.type = 'file'
}

Of all the answers here this is the fastest solution. No input clone, no form reset!

I checked it in all browsers (it even has IE8 support).

Maxmaxmaximus
  • 1,834
  • 1
  • 16
  • 16
  • 4
    Is there any specific reason to reset the `input.type` too? Setting just the value to `''` is giving the expected result. – Harshita Sethi Mar 03 '17 at 13:05
  • 1
    This needs some more upvotes or something, I took far too long to find this answer, this is the only one I found that works on IE. – sch Jan 04 '18 at 12:27
  • 1
    input.value = '' throws an exception to the console in IE11. However resetting input.type works on all browsers without any error. – Miroslav Jasso Nov 15 '18 at 07:08
  • This answer is not good enough. If the input is set as `required`, resetting the field should make the field invalid again. Unfortunately in this case, it is still valid, so the form will submit, although with no value. – pepkin88 Apr 24 '19 at 16:50
  • I would set value to `null`, but basically same thing. – CodeFinity May 26 '19 at 22:38
  • Why the test on safari? And if the test is true, no reset? – artfulrobot May 14 '21 at 16:17
53

In case you have the following:

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

then just do:

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

to reset the file control.

sstauross
  • 2,056
  • 1
  • 24
  • 48
45

Another solution (without selecting HTML DOM elements )

If you added 'change' event listener on that input, then in javascript code you can call (for some specified conditions):

event.target.value = '';

For example in HTML:

<input type="file" onChange="onChangeFunction(event)">

And in javascript:

onChangeFunction(event) {
  let fileList = event.target.files;
  let file = fileList[0];
  let extension = file.name.match(/(?<=\.)\w+$/g)[0].toLowerCase(); // assuming that this file has any extension

  if (extension === 'jpg') {
    alert('Good file extension!');
  }
  else {
    event.target.value = '';
    alert('Wrong file extension! File input is cleared.');
  }
indreed
  • 1,055
  • 11
  • 9
  • Another way to angular2: https://stackoverflow.com/questions/40165271/how-to-reset-selected-file-with-input-tag-file-type-in-angular-2 – Belter Nov 23 '17 at 07:37
  • This will only work on filenames which contain just a single `.` in front of file extension. – Ma Kobi Dec 19 '17 at 08:13
  • That's right, I have edited the code and provided more universal approach to get a file extension. – indreed Jan 24 '18 at 15:28
44

You can just clone it and replace it with itself, with all events still attached:

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

and

var input = $("#control");

function something_happens() {
    input.replaceWith(input.val('').clone(true));
};

Thanks : Css-tricks.com

pixparker
  • 2,316
  • 20
  • 18
  • 1
    Unfortunately this doesn't reset input value, see [this jsFiddle](http://jsfiddle.net/698svryg/). For a better solution, see [this answer](http://stackoverflow.com/a/13351234/3549014). – Gyrocode.com Jul 31 '15 at 17:40
  • 1
    @Gyrocode.com This jsFiddle doesn't work if the image is uploaded second time after reset. – Sarthak Singhal Aug 07 '15 at 09:40
  • @SarthakSinghal, that's exactly what I meant. The answer above (demonstrated by this [jsFiddle](http://jsfiddle.net/698svryg/)) doesn't work because once file is upload the second time the reset stops working. I'm surprised this incorrect answer got so many votes. For a better solution, see [this answer](http://stackoverflow.com/a/13351234/3549014) or [this answer](http://stackoverflow.com/a/31751943/3549014). – Gyrocode.com Aug 07 '15 at 14:19
  • 2
    @SarthakSinghal, Unfortunately you wrote the wrong code, you should have done http://jsfiddle.net/cL1LooLe – Roger Russel Sep 14 '15 at 23:08
  • 2
    @RogerRussel: Exactly... I was wondering myself how come upper answers were saying that it only works once which is a clear indicator that some sort of reference is being lost. And that was actually the case because the initially created the input reference that was later replaced with a new input element. – Robert Koritnik Oct 23 '15 at 21:10
  • 1
    Just resetting the `value` like in other answers seems much more straightforward than manipulating the DOM. – CodeFinity May 26 '19 at 22:39
32

SOLUTION

The following code worked for me with jQuery. It works in every browser and allows to preserve events and custom properties.

var $el = $('#uploadCaptureInputFile');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();

DEMO

See this jsFiddle for code and demonstration.

LINKS

See How to reset file input with JavaScript for more information.

Gyrocode.com
  • 51,125
  • 13
  • 124
  • 164
30

Particularly for Angular

document.getElementById('uploadFile').value = "";

Will work, But if you use Angular It will say "Property 'value' does not exist on type 'HTMLElement'.any"

document.getElementById() returns the type HTMLElement which does not contain a value property. So, cast it into HTMLInputElement

(<HTMLInputElement>document.getElementById('uploadFile')).value = "";

EXTRA :-

However, we should not use DOM manipulation (document.xyz()) in angular.

To do that angular has provided @VIewChild, @ViewChildren, etc which are document.querySelector(), document.queryselectorAll() respectively.

Even I haven't read it. Better to follows expert's blogs

Go through this link1, link2

P Satish Patro
  • 2,033
  • 1
  • 19
  • 33
27

Resetting a file upload button is so easy using pure JavaScript!

There are few ways to do it, but the must straightforward way which is working well in many browser is changing the filed value to nothing, that way the upload filed gets reset, also try to use pure javascript rather than any framework, I created the code below, just check it out (ES6):

function resetFile() {
  const file = document.querySelector('.file');
  file.value = '';
}
<input type="file" class="file" />
<button onclick="resetFile()">Reset file</button>
Alireza
  • 83,698
  • 19
  • 241
  • 152
15

I use for vuejs

   <input
          type="file"
          ref="fileref"
          @change="onChange"/>

this.$refs.fileref.value = ''
anson
  • 1,054
  • 10
  • 12
9

The reseting input file is on very single

$('input[type=file]').val(null);

If you bind reset the file in change other field of the form, or load form with ajax.

This example is applicable

selector for example is $('input[type=text]') or any element of the form

event click, change, or any event

$('body').delegate('event', 'selector', function(){
     $('input[type=file]').val(null) ;
});
Ivan Fretes
  • 549
  • 6
  • 9
7

There are many approaches and i will suggest to go with ref attachment to input.

<input
    id="image"
    type="file"
    required
    ref={ref => this.fileInput = ref}
    multiple
    onChange={this.onFileChangeHandler}
/>

to clear value after submit.

this.fileInput.value = "";
adiga
  • 28,937
  • 7
  • 45
  • 66
Sourabh Bhutani
  • 465
  • 5
  • 14
6

My Best Solution

$(".file_uplaod_input").val('');  // this is working best ):
6

I miss an other Solution here (2021): I use FileList to interact with file input.

Since there is no way to create a FileList object, I use DataTransfer, that brings clean FilleList with it.

I reset it with:

  file_input.files=new DataTransfer().files  

In my case this perfectly fits, since I interact only via FileList with my encapsulated file input element.

halfbit
  • 2,999
  • 1
  • 29
  • 40
5

With IE 10 I resolved the problem with :

    var file = document.getElementById("file-input");
    file.removeAttribute('value');
    file.parentNode.replaceChild(file.cloneNode(true),file);

where :

<input accept="image/*" onchange="angular.element(this).scope().uploadFile(this)" id="file-input" type="file"/>
Alvaro Joao
  • 7,787
  • 9
  • 42
  • 70
5

document.getElementById("uploadCaptureInputFile").value = "";
Jalaleddin Hosseini
  • 1,093
  • 1
  • 12
  • 19
4

Just use:

$('input[type=file]').val('');
Casimir Crystal
  • 18,651
  • 14
  • 55
  • 76
deepak shinde
  • 57
  • 1
  • 1
4

With angular you can create a template variable and set the value to null

<input type="file" #fileUploader />
<button (click)="fileUploader.value = null">Reset from UI</button>

Or you can create a method to reset like this

component.ts

  @ViewChild('fileUploader') fileUploader:ElementRef;

  resetFileUploader() { 
    this.fileUploader.nativeElement.value = null;
  }

template

<input type="file"/>
<button (click)="resetFileUploader()">Reset from Component</button>

stackblitz demo

malbarmavi
  • 18,795
  • 4
  • 45
  • 73
3
<input type="file" id="mfile" name="mfile">
<p>Reset</p>

<script>
$(document).ready(function(){
$("p").click(function(){

            $("#mfile").val('');
            return false;

    });
});

w.Daya
  • 41
  • 1
  • 6
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. [From Review](/review/low-quality-posts/25734470) – double-beep Mar 31 '20 at 09:50
  • $("#mfile").val('') will empty the file input field. – w.Daya Jan 14 '21 at 08:47
2

You can´t reset that since it is an read-only file. you can clone it to workaround the problem.

Ducaz035
  • 2,798
  • 2
  • 21
  • 40
2

You should try this:

$("#uploadCaptureInputFile").val('');
Muhammad Awais
  • 3,310
  • 1
  • 34
  • 32
2

This could be done like this

var inputfile= $('#uploadCaptureInputFile')
$('#reset').on('click',function(){
inputfile.replaceWith(inputfile.val('').clone(true));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />
<a href="" id="reset">Reset</a>
Fraz Abbas
  • 148
  • 9
1

jQuery solution:

    $('input').on('change',function(){
                $(this).get(0).value = '';
                $(this).get(0).type = '';
                $(this).get(0).type = 'file';
            });
panatoni
  • 525
  • 5
  • 11
  • Consider padding this answer out to explain how it works. – Bugs Feb 03 '17 at 13:11
  • @Bugs guess this speaks for itself. When the file input's `on change` event is triggered the value gets cleared. The type of the input gets resetted from none to file. –  Feb 13 '17 at 08:49
  • 2
    @Jordy yes I know what it does :) I was just thinking that with a dozen other answers it would be worth trying to make it stand out. It appeared whilst I was reviewing. They could in fact copy your comment to pad it out that bit more. It's always worth trying to explain why you feel the code fixes the OPs problem. – Bugs Feb 13 '17 at 09:02
1

I faced the issue with ng2-file-upload for angular. if you are looking for the solution in angular 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 = '';`

};

0

If you have several files in your form but only want one of them to be reset:

if you use boostrap, jquery, filestyle to display the input file form :

$("#"+idInput).filestyle('clear');
0
var fileInput = $('#uploadCaptureInputFile');
fileInput.replaceWith(fileInput.val('').clone(true));
Kld
  • 6,430
  • 3
  • 33
  • 49
0

Works for dynamic controls too.

Javascript

<input type="file" onchange="FileValidate(this)" />

function FileValidate(object) {
    if ((object.files[0].size / 1024 / 1024) > 1) {   //greater than 1 MB         
        $(object).val('');
    }     
}

JQuery

<input type="file" class="UpoloadFileSize">

$(document).ready(function () {

    $('.UpoloadFileSize').bind('change', function () {                
        if ((this.files[0].size / 1024000) > 1.5) { //greater than 1.5 MB
            $(this).val('');
            alert('Size exceeded !!');
        }
    });

});
Arun Prasad E S
  • 7,342
  • 6
  • 61
  • 75
0

function resetImageField() {
    var $el = $('#uploadCaptureInputFile');                                        
    $el.wrap('<form>').closest('form').get(0).reset();
    $el.unwrap();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />
<button onclick="resetImageField()">Reset field</button>
lewis4u
  • 11,579
  • 13
  • 79
  • 118