【问题标题】:Upload the image in HTML and get the image path上传 HTML 格式的图片并获取图片路径
【发布时间】:2019-04-29 16:47:15
【问题描述】:

我在FileReader实例的onload回调函数中使用<input type="file" accept="image/*">上传图片和图片的base64编码,成功。但是当我将此 base64 编码分配给另一个数据变量时,它会失败,并且我无法获得它的值。这是为什么?你可以帮帮我吗?谢谢!

<div id="app">
  <input type="file" accept="image/*" @change="changeFile" ref="file">  
  <img :src="imgUrl" ref="image">
  <div :style="{background: 'url(' + imgUrl + ')'}"></div>
  <p>{{imgUrl}}</p>
</div>

var vm = new Vue({
  el: '#app',
  data: {
    imgUrl: ''
  },
  methods: {
    changeFile() {
      let reader = new FileReader();
      let file = this.$refs.file;
      let image = this.$refs.image;
      reader.readAsDataURL(file.files[0]);
      reader.onload = function(e) {
        let temp = this.result;
        this.imgUrl = temp;
        image.src = temp;
      }
    }
  }
})

【问题讨论】:

  • 您想在其他地方使用您的 base64 数据吗?
  • 是的,我也想用这个base64数据作为背景图片。 @Sebastian Waldbauer
  • 您的posted 代码正在运行。您可以访问变量 temp 并使用函数将其发送到某个地方。
  • 是的,&lt;img&gt; 有效,但 &lt;div&gt; 不显示背景图像,&lt;p&gt; 不显示 base64 数据。如果您查看元素,您会发现它们没有获取 base64 数据。如上图所示。@Sebastian Waldbauer

标签: javascript html vue.js


【解决方案1】:

因为thisJS界的坏小子:

<div id="app">
  <input type="file" accept="image/*" @change="changeFile" ref="file">  
  <img :src="imgUrl" ref="image">
  <div :style="{background: 'url(' + imgUrl + ')'}"></div>
  <p>{{imgUrl}}</p>
</div>

var vm = new Vue({
  el: '#app',
  data: {
    imgUrl: ''
  },
  methods: {
    changeFile() {
      let reader = new FileReader();
      let file = this.$refs.file;
      let image = this.$refs.image;

      // keep the "this" for later use:
      let thisComp = this;

      reader.readAsDataURL(file.files[0]);
      reader.onload = function(e) {
        let temp = this.result;
        thisComp.imgUrl = temp;
        image.src = temp;
      }
    }
  }
})  

在您的情况下,this 指的是已使用this 的函数的调用者(这里是FileReader 对象reader),这就是为什么数据imgUrl 根本没有改变的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    相关资源
    最近更新 更多