3

I'm having some problems rendering an image in a HTML element. I think the solution might be simple for experienced front end devs. I have a Vuetify component that lets user input a profile image:

<v-form>
   <v-avatar size="144">
       <v-icon hidden ref="default_icon" size="144">account_circle</v-icon>
       <img ref="my_img" style="display: none;" :src="my_photo.name">
       <v-btn @click="$refs.my_input.click()" class="img_btn" absolute right small fab dark color="pink">
           <v-icon dark>add</v-icon>
       </v-btn>
       <input ref="my_input" hidden type="file" accept="image/*" @change="onFileChange($refs.my_input)">
   </v-avatar>
</v-form>

When the element calls onFileChange it pass the HTML element to the function.

onFileChange(event) {
    this.my_photo = event.files[0]
    console.log(this.my_photo)
    this.$refs.default_icon.style.display = "none"
    this.$refs.my_img.style.display = "inline"
}

So now the function replaces the icon with the img tag. I want to fill the image tag with the image that the user inputs. this.my_photo is a File type variable. Does anyone know how to do this? Regards for everyone!

1 Answer 1

5

my_photo.name is literally just the name of the uploaded image. You need to convert the uploaded image to a valid format for the image src.

You can do this a couple ways using either FileReader.readAsDataURL() or URL.createObjectURL(). These create source representations that the image tag can use.

Keep in mind that if you plan on uploading this image to a server you will need to keep a reference to event.target.files[0].

Here an example using URL.createObjectURL().

new Vue({
  el: "#app",
  data: {
    my_photo: '',
  },
  methods: {
    onFileInput(event) {    	   
      const data = URL.createObjectURL(event.target.files[0]);
      this.my_photo = data;
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
  <input type="file" @change="onFileInput($event)">
  <img :src="my_photo" alt="">
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! this is exactly what i was looking for. I really appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.