16

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

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

zubair-0
  • 988
  • 8
  • 15
  • 1
    Possible duplicate of [How to detect input type=file "change" for the same file?](https://stackoverflow.com/questions/4109276/how-to-detect-input-type-file-change-for-the-same-file) – Rwd Jan 10 '19 at 09:06
  • It's not a change if it's the same file. One option would be clear the field when the input is clicked so that when they select a file it's always a `change`. – Rwd Jan 10 '19 at 09:07
  • 1
    Not a duplicate of that question since that is in jquery and this is in vuejs. Both have different ways to access the fields. You are right about clearing the field on click because I wanna trigger the change event every time a file is uploaded – zubair-0 Jan 10 '19 at 09:42

4 Answers4

38

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>
T. Dirks
  • 3,566
  • 1
  • 19
  • 34
zubair-0
  • 988
  • 8
  • 15
  • 9
    even easier - put the `this.$refs.imageUploader.value = '';` to the end of the `uploadImageFile` method :) – grreeenn May 02 '20 at 22:55
4

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=''">
Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132
0

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>
hermeslm
  • 1,535
  • 16
  • 13
0

I fix it by key. For exampleenter image description here

I hope this helps you

Sergey
  • 126
  • 7