How to reset/clear file Input
Asked Answered
P

9

32

I am stuck with this problem from resetting an image file from input type=file. This is the scenario, I set an image and then I clicked the 'Cancel' button (which means it was reset), and then I will set again the same image, it will not set. I do not know why but I think it is a bug.

Here is my code for resetting the image/form.

resetImage() {
    this.$refs.addImageForm.reset()
    this.dialog = ''
    this.imgSrc = ''
    this.fileName = ''
    this.imgUrl = ''
    this.file = ''
}

I am using Vue.js and Vuetify if that helps. I hope you can help me. I am stuck with this problem

HERE IS THE HTML

<template>
    <v-dialog
        persistent
        v-model="dialog"
        width="600"
    >
    <template v-slot:activator="{ on }">
        <v-btn depressed color="primary" v-on="on">
        <v-icon class="pr-2">check</v-icon>Approve
        </v-btn>
    </template>
    <v-card>
        <div class="px-4 pt-3">
            <span class="subheading font-weight-bold">Approve Details</span>
            <input
                ref="image"
                type="file"
                name="image"
                accept="image/*"
                style="display: none;"
                @change="setImage"
            />
            <v-layout row wrap align-center>
                <v-flex xs12 class="pa-0">
                <div class="text-xs-center">
                    <v-img :src="imgUrl" contain/>
                </div>
                <VueCropper
                    :dragMode="'none'"
                    :viewMode="1"
                    :autoCrop="false"
                    :zoomOnWheel="false"
                    :background="false"
                    :src="imgSrc"
                    v-show="false"
                    ref="cropper"
                />
                <v-form ref="addImageForm" lazy-validation>
                    <v-layout row wrap class="pt-2">
                    <v-flex xs12>
                        <v-text-field
                        outline
                        readonly
                        :label="imgSrc ? 'Click here to change the image' : 'Click here to upload image'"
                        append-icon='attach_file'
                        :rules="imageRule"
                        v-model='fileName'
                        @click='launchFilePicker'
                        ></v-text-field>
                    </v-flex>
                    </v-layout>
                </v-form>
                </v-flex>
            </v-layout>
        </div>
        <v-divider></v-divider>
        <v-card-actions class="px-4">
        <v-btn
            large
            flat
            @click="resetImage()"
        >Cancel</v-btn>
        <v-spacer></v-spacer>
        <v-btn
            large
            depressed
            color="primary"
            @click="approveCashout"
            :loading="isUploading"
        >Approve</v-btn>
        </v-card-actions>
    </v-card>
    </v-dialog>
</template>
Pocahontas answered 9/1, 2020 at 6:40 Comment(3)
Can you show your HTML as well?Cchaddie
Sure2 wait I will editPocahontas
Updated and added htmlPocahontas
L
67

You can use ref to reset the file uploader value.

this.$refs.fileupload.value = null;

codepen - https://codepen.io/Pratik__007/pen/MWYVjqP?editors=1010

Limy answered 9/1, 2020 at 7:40 Comment(8)
In my setup - Vue 2.6.12, Vuetify 2.4.2, Typescript 3.9.7 this results in a 'Vue warning': "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. [...]" It still works, but so does the answer below (besides vs code reporting a nonexistent error)Phyfe
this throws an error Cannot set property 'value' of undefined"Posture
@MohamedRaza Make sure you have added ref in input fieldLimy
@PatelPratik i already added ref in my inputPosture
@MohamedRaza Can you try to console log this.$refs.fileupload and check it's giving value or notLimy
For this.$refs.fileupload.value=null; to work, you need to assign ref on the input as well like this <input ref="fileupload" type="file" />.Borek
Yup it's required. It's there in codepen and question.Limy
Works like charm and no warning, Vue.js 2.6.11Algetic
M
17

To reset the input, I let vue rerender it. Just add a key to the input and change the value of the key whenever you want the file input to be cleared.

Like so:

window.app = new Vue({
  el: '#app',
  data: {
    fileInputKey: 0
  },
  methods:{
    inputChange() {
      console.log('files chosen');
    },
    clear() {
        this.fileInputKey++;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="file" @change="inputChange($event)" :key="fileInputKey"/>
  <button @click="clear">Clear</button>
</div>
Mendez answered 24/2, 2021 at 9:30 Comment(1)
Of all the solutions, this was the only one that works :)Hieroglyphic
H
13

I tried several suggestions I found on Stackoverflow, but in my project there were several errors. What solved my problem was:

<input type="file" ref="inputFile"/>
this.$refs.inputFile.reset();

This code above resets the field values.

Hedgerow answered 23/9, 2020 at 12:40 Comment(5)
the above answer throws some warning. this one should be the accepted answerCretin
I get TypeError: this.$refs.inputFile.reset is not a function when I use this, but using this.$refs.inputFile.value=null worked for me.Foreandaft
this.$refs.inputFile.$el.value=null is betterVagabond
work like a charm, this is the right way how to reset the file input form on vuetify. ThanksIntelligent
This does not work for me, says reset is not a function and removing brackets doesn't do anything. Neither warning nor error and nothing happens, Vue.js 2.6.11Algetic
O
7

I also came to this problem and could not reset the value. after going through the code of all previous projects and modifying them I got a lot of methods through which a file input could be reset. one of the way is do is to capture the event object if you want to perform it after handling some code. another way is to change the type of the input element and change it back again.

<div id="app">
  <input type="file" @change="onFilePicked" ref="file">
  <button @click="clear()">Cancel</button>
</div>
var v = new Vue({
    el:'#app',

    data:{},

    methods:{
        clear() { 
            this.$refs.file.type='text';    
            this.$refs.file.type='file'; 
        },
        onFilePicked(event){
            //if you directly want to clear the file input after handling 
            //some code........
            event.target.value=null;
            //OR
            event.target.value='';
        }
    },
});
Odorous answered 21/8, 2021 at 0:14 Comment(0)
F
4

For Composition api

<input type="file" 
       class="custom-file-input" 
       id="customFileLang" 
       lang="en" 
       accept="image/*"
       :class="{ 'is-invalid': errors && errors.images }"
       @change="previewImg" multiple
>

Inside setup function:

const imgInput = ref(null) // for input type file

const previewImg = (event) => {
    imgInput.value = event
    // rest of code to preview img
}

const uploadImage = () => {
    //on success
    imgInput.value.target.value = null //reset input type file
}
Fetiparous answered 24/9, 2021 at 8:14 Comment(0)
S
3

Vue 2 or 3 or Nuxt with composition API, you can use this to reset a form:

<template>
  <form ref="refForm">
    <input value="hello world" />
  </form>
</template>

<script setup>
const refForm = ref(null)

onMounted(() => {
  setInterval(() => {
    refForm.value.reset()
  }, 3000) // in 3 seconds will reset the form
})
</script>

to reset only the input file, use this code:

<template>
  <input ref="refFile" type="file" @change="reset" />
</template>

<script setup>
const refFile = ref(null)

const reset = () => {
  setInterval(() => {
    refFile.value.value = ''
  }, 3000) // in 3 seconds will reset the file input
}
</script>
Sarver answered 12/3, 2023 at 14:57 Comment(1)
thanyou, im forgot when using ref must use value.value haha.Cinquain
A
2

If you are using Vue 3 Composition API, here's how I was able to do it:

<template>
  <div>
    <input ref="fileInput" type="file" />

    <button @click.prevent="clearFiles">Clear files</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue"

const fileInput = ref<HTMLInputElement | null>(null)

function clearFiles() {
  fileInput.value!.value = ""
}
</script>
Amil answered 5/7, 2023 at 17:59 Comment(0)
B
0

I try mutilpe ways on vue, the best way is:

define this method:

removePic(inp) {
  if (this.$refs[inp].files.length === 0) return
  this.$refs[inp].files = []
  delete this.body[inp]
  this.$refs[`${inp}_preview`].src = ''
},

in the template use as this:

                   <b-form-file
                      ref="pic"
                      name="pic"
                      accept="image/jpeg, image/png, image/gif"
                    />

                  <feather-icon
                    icon="XIcon"
                    size="18"
                    class="text-primary stroke-current"
                    @click="removePic('pic')"
                  />

                 <div>
                  <img ref="pic_preview" src="#" alt="select" />
                </div>
Betwixt answered 16/6, 2022 at 18:37 Comment(0)
C
0

This worked for me: inputfile.files = new DataTransfer().files;

Corked answered 15/4, 2023 at 11:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.