VueJS: Input file selection event not firing upon selecting the same file

Viewed 6828

How can we file input detect change on SAME file input in Vue Js

<input ref="imageUploader" type="file" @change="uploadImageFile">

3 Answers

We can add @click event and then clear the value of the file input

<template>
    ....
        <input ref="imageUploader" type="file" accept=".jpg, .jpeg" @click="resetImageUploader" @change="uploadImageFile">
    ....
</template>

<script>
    export default {
        methods: {
            resetImageUploader() {
                this.$refs.imageUploader.value = '';
            },
            uploadImageFile() {
                ....
            }
        }
    }
</script>

Same thing as @zubair's answer but for vue 3 and a bit more convenient:

<input type="file" @change="renderImage($event)" @click="$event.target.value=''">

The @zubair-0 and @grreeenn's answers are totally valid, Here you can have an implementation initializing the input value with an empty string after the uploaded file is processed because the event only is fired when the value changed, you can do this in Vue 3 using the Template Refs.

<template>
  <input
      ref="imageUploader"
      type="file"
      class="custom-file-input"
      name="file-upload"
      accept="image/png, image/gif, image/jpeg"
      @change="uploadImageFile($event)"
    >
</template>
<script>
  import { ref } from 'vue'
  export default {
     setup() {
       const imageUploader = ref(null)
       const uploadImageFile = (event) => {
          console.log('File loaded...')
          // We initialize the input value, this is the trick
          imageUploader.value.value = ''
       }
       return {
         imageUploader,
         uploadImageFile
       }
   }
 }
</script>
Related