在上传VUEjs之前预览图像

时间:2018-03-05 08:17:17

标签: javascript vue.js bootstrap-vue

我知道这个问题已经被问到了。但我不知道如何在vuejs中使用代码。我尝试了很多,但没有任何结果。 我还添加了我的代码。 有人可以帮帮我吗?这是我的代码。 感谢

HTML

<script>
export default {
    name: 'listImage',
    data() {
        return {
            selectedFile: null,
            images: [],
            image_fields: ['id', 'name'],
            total_images: 1               
        }
    },
    methods: {
        fileSelected(evt) {
            evt.preventDefault()
            console.log(evt);
            this.selectedFile = evt.target.files[0]
        },
        uploadImage() {
            var data = new FormData();
            data.append('image', this.selectedFile, this.selectedFile.data)
            var token = sessionStorage.getItem('token')
            const config = {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
            window.API.post('https://110.10.56.10:8000/images/?token=' + token, data, config)
                .then(response => this.$router.push('/listImage'))
                .catch((error) => {
                    console.log(JSON.stringify(error))
                })
        }
    }
}

JS

{{1}}

1 个答案:

答案 0 :(得分:33)

请记住,浏览器无法显示所有图像类型,(例如:tiff不会使用此方法)。

还有几个步骤:

&#13;
&#13;
const vm = new Vue({
  el: '#app',
  data() {
    return {
      url: null,
    }
  },
  methods: {
    onFileChange(e) {
      const file = e.target.files[0];
      this.url = URL.createObjectURL(file);
    }
  }
})
&#13;
body {
  background-color: #e2e2e2;
}

#app {
  padding: 20px;
}

#preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

#preview img {
  max-width: 100%;
  max-height: 500px;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <input type="file" @change="onFileChange" />

  <div id="preview">
    <img v-if="url" :src="url" />
  </div>
</div>
&#13;
&#13;
&#13;

相关问题