用户选择头像后, 要在前端做预览的实现方式
- 展示的上传按钮
![]()
<input type="file" accept="image/*" style="display: none" @change="onFileChange" ref="iptRef"/>
<el-button size="small" type="primary" icon="el-icon-plus" @click="picBtn">点击上传
- 具体实现的代码
// 点击上传图片
picBtn() {
this.$refs.iptRef.click()
},
// 上传图片事件
onFileChange(e) {
const files = e.target.files
// 没有选中文件
if (files.length === 0) {
this.avatar = ''
this.$message.warning('请选择你要上传的头像')
} else {
/**
* 方式1: 使用FileReader来读取选择的前端文件, 转换为base64字符串, 给img标签渲染
*
// 创建文件读取对象
const fileDoc = new FileReader()
// 调用readAsDataURL函数,读取文件
fileDoc.readAsDataURL(files[0])
// 监听fileDoc的onload事件
fileDoc.onload = (e) => {
// 通过e.target.result获取到 读到的内容,值是base64格式的字符串
this.avatar = e.target.result
}
*/
/**
* 方式2
// 使用URL.createObjURL()来转换文件变成图片地址(纯前端本地)
this.avatar = URL.createObjectURL(files[0])
*/
}
}

浙公网安备 33010602011771号