Preview image before its uploaded using vuetify "<v-file-input>"?

Viewed 2405

This is what I have right now

      <v-file-input
            v-model="image"
            type="file"
            class="input"
            label="Upload license"
            hint="Add a picture of youre license"
            outlined
            dense
            @change="onFileChange"
          />

          <v-img :src="image" />

Just so you know, I know how to do this with the "", it kinda looks like this:

createImage (file) {
  const image = new Image()
  const reader = new FileReader()
  const vm = this

  reader.onload = (e) => {
    vm.image = e.target.result
    console.log(vm.image)
  }
  reader.readAsDataURL(file)
   },        
 onFileChange (e) {
  const files = e.target.files || e.dataTransfer.files
  if (!files.length) { return }
  this.createImage(files[0])
},

and just call to onFileChange on the input tag like @change="onFileChange"

2 Answers

<v-file-input> returns the file(s) itself on @change event unlike the native <input type="file" />. So in that case e.target.files does not exist there, e is the file itself. Also I would recommend not to share image for both v-file-input and v-img. v-img expects an url and v-file-input expects a file. Instead, I would recommend splitting it to 2 different variables like image and imageUrl.

Below you can see an example:

<v-file-input v-model="image" outlined dense @change="onFileChange" />
<v-img :src="imageUrl" />
data() {
  return {
    image: undefined,
    // to save image url
    imageUrl: ""
  };
},
methods: {
  createImage(file) {
    const reader = new FileReader();

    reader.onload = e => {
      this.imageUrl = e.target.result;
    };
    reader.readAsDataURL(file);
  },
  onFileChange(file) {
    if (!file) {
      return;
    }
    this.createImage(file);
  }
}

Here is a working example: https://codepen.io/onelly/pen/xxOBJjL

Not sure if you're doing right. You've created object url on this.url, so you should use it instead of image as src value of img tag.

<v-img :src="url" />
Related