在上传图像之前预览图像VUE.js [英] Preview an image before it is uploaded VUEjs
本文介绍了在上传图像之前预览图像VUE.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道有人问过这个问题.但是我不知道如何在vuejs中使用代码.我尝试了很多,但没有任何结果. 我还添加了我的代码. 有人可以帮帮我吗?这是我的代码. 谢谢
I know this question has been asked. But I have no idea how to use the code in vuejs. I tried a lot but without any results. I also added my code. Can some one please help me? This is my code. Thanks
html
<template>
<div class="fileUpload">
<b-container fluid>
<h4>Image Overview</h4>
<b-button @click="$refs.fileInput.click()" class="btn-right">Select an image</b-button>
<b-table @row-clicked="viewImage" striped hover :items="images" :fields="image_fields"></b-table>
<input style="display: none" ref="fileInput" type="file" @change="fileSelected" enctype="multipart/form-data">
<b-button variant="success" class="btn-right" @click="uploadImage" method="post">Upload image</b-button>
</b-container>
</div>
js
<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))
})
}
}
}
推荐答案
请记住,浏览器无法显示所有图像类型(例如:tiff不适用于此方法).
Please keep in mind that a browser cannot display all image types, (eg: a tiff won't work with this method).
有几个步骤:
- 使用
@change
侦听器输入文件 - 在onChange中,您创建对象URL
- 使用此URL显示图像
- Have a file input with a
@change
listener - In the onChange, you create an object URL
- Use this URL to display the image
const vm = new Vue({
el: '#app',
data() {
return {
url: null,
}
},
methods: {
onFileChange(e) {
const file = e.target.files[0];
this.url = URL.createObjectURL(file);
}
}
})
body {
background-color: #e2e2e2;
}
#app {
padding: 20px;
}
#preview {
display: flex;
justify-content: center;
align-items: center;
}
#preview img {
max-width: 100%;
max-height: 500px;
}
<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>
这篇关于在上传图像之前预览图像VUE.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文