使用Vuejs从本地存储上传图像

时间:2017-10-18 08:40:23

标签: vue.js vuejs2 vue-component

当您点击"选择文件"并选择要上传的图像,但会出现路径。只有在您单击"选择文件"再一次。

如何解决此问题并在选择文件时上传?

非常感谢任何帮助。谢谢。



new Vue({
  el: '.app',
  data: {
  userImage: ''
  },
  methods: {
    onFileChange(e) {
        var files = e.target.files || e.dataTransfer.files
        if (!files.length) {
          return
        }
        this.createImage(files[0])
      },
      createImage(file) {
        var reader = new FileReader()
        var vm = this

        reader.onload = (e) => {
          vm.userImage = e.target.result
        }
        reader.readAsDataURL(file)
      },
       removeImage: function (e) {
         this.userImage = ''
       }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div class="col-xl-3 col-lg-3 col-md-4 col-sm-6 col-xs-6 text-center app">

  <img class="profile-image" :src="userImage" />

  <div v-if="!userImage">
    <input type="file" round class="change-profile-image" @change="onFileChange" />
  </div>
  <div v-else>
    <button class="delete-profile-image" color="secondary" icon="delete" @click="removeImage">Delete</button>
  </div>

</div>
&#13;
&#13;
&#13;

我的代码JSfiddle

1 个答案:

答案 0 :(得分:0)

您不应该依赖于收听click事件。你要找的是change事件,即使用@change代替@click

<input type="file" round class="change-profile-image" @change="onFileChange" />

请参阅更新的小提琴:https://jsfiddle.net/hrtzezk8/5/或下面的概念验证片段:

new Vue({
  el: '.app',
  data: {
  userImage: ''
  },
  methods: {
    onFileChange(e) {
        var files = e.target.files || e.dataTransfer.files
        if (!files.length) {
          return
        }
        this.createImage(files[0])
      },
      createImage(file) {
        var reader = new FileReader()
        var vm = this

        reader.onload = (e) => {
          vm.userImage = e.target.result
        }
        reader.readAsDataURL(file)
      },
       removeImage: function (e) {
         this.userImage = ''
       }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div class="col-xl-3 col-lg-3 col-md-4 col-sm-6 col-xs-6 text-center app">

  <img class="profile-image" :src="userImage" />

  <div v-if="!userImage">
    <input type="file" round class="change-profile-image" @change="onFileChange" />
  </div>
  <div v-else>
    <button class="delete-profile-image" color="secondary" icon="delete" @click="removeImage">Delete</button>
  </div>

</div>