简体   繁体   English

使用 vuetify 在上传之前预览图像“<v-file-input> “?

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

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"只需在输入标签上调用 onFileChange ,例如 @change="onFileChange"

<v-file-input> returns the file(s) itself on @change event unlike the native <input type="file" /> . <v-file-input>与原生的<input type="file" />不同,在@change事件上返回文件本身。 So in that case e.target.files does not exist there, e is the file itself.所以在那种情况下e.target.files不存在, e是文件本身。 Also I would recommend not to share image for both v-file-input and v-img .此外,我不会推荐给共享image两个v-file-inputv-img v-img expects an url and v-file-input expects a file. v-img需要一个 url,而v-file-input需要一个文件。 Instead, I would recommend splitting it to 2 different variables like image and imageUrl .相反,我建议将其拆分为 2 个不同的变量,例如imageimageUrl

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这是一个工作示例: 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.您已经在this.url上创建了对象 url ,因此您应该使用它而不是image作为img标签的src值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM