1.通过input标签实现
html部分
input标签属性配置
type属性
,将该属性的值设置为file
accept属性
,该属性用来限制上传文件的类型,我们上传图片因此将该属性的值设置为image
ref属性
,在vue中ref用来获取dom,该值用来在js中通过this.$refs.xxx 来获取dom节点,我们的例子中将该值设置为imgInput
监听change事件
,当事件触发时调用uploadImg
函数
<template>
<div>
<label>图片预览</label>
<img v-if="imgBase64Value!==''" :src="imgBase64Value" />
<br>
<input type="file" accept="image" ref="imgInput" @change="uploadImg"/>
</div>
</template>
js部分实现步骤
- 通过ref获取文件
- 创建new fileReader对象reader
- 利用readAsDataURL函数,读取通过ref获取的文件的内容
- 在onload事件的回调函数中获取转为base64的值,例子中回调函数中res.target.result的值就是图片转为base64的值
<script>
export default {
name: 'uploadImg',
data () {
return {
imgBase64Value: ''
}
},
methods: {
uploadImg () {
const imgFile = this.$refs.imgInput.files[0]
const reader = new FileReader()
reader.readAsDataURL(imgFile)
reader.onload = (res) => {
this.imgBase64Value = res.target.result
}
}
}
}
</script>
2.通过element-ui组件el-upload实现
html部分
属性说明参照element-ui组件el-upload属性介绍
<template>
<div>
<label>图片预览</label>
<img v-if="imgBase64Value!==''" :src="imgBase64Value" />
<br>
<el-upload
ref="upload"
class="hideinput"
list-type="picture-card"
:auto-upload="false"
:limit="1"
accept="image/jpeg,image/png"
action=""
:on-change="uploadChange">
<i class="el-icon-plus" />
</el-upload>
</div>
</template>
js部分
实现过程与通过input标签获取基本相同,不同的地方是获取图片文件的过程,el-upload组件中的on-change事件有两个参数file和fileList;例子中一次只上传一张图片所以直接通过参数file中的raw属性获取文件内容,如果支持多张图片可以通过fileList获取每个图片文件的内容
<script>
export default {
name: 'uploadImg',
data () {
return {
imgBase64Value: ''
}
},
methods: {
uploadChange (file, fileList) {
const imgFile = file.raw
const reader = new FileReader()
reader.readAsDataURL(imgFile)
reader.onload = (res) => {
this.imgBase64Value = res.target.result
}
}
}
}
</script>