需求:利用 element ui 的 upload 组件把图片转化为 base64 编码进行头像上传
话不多说,直接上代码
HTML模块代码如下:
<el-upload
list-type="picture"
action
accept=".jpg, .png"
:auto-upload="false"
:file-list="fileList"
:before-upload="beforeUpload"
:on-change="getFile"
:on-success="handleAvatarSuccess"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<div v-else class="avatar-container">
<i class="el-icon-s-custom avatar-uploader-icon"></i>
</div>
</el-upload>
JS模块代码如下:
// 获取文件信息
getFile(file, fileList) {
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!');
return false;
}
this.getBase64(file.raw).then((res) => {
this.imageUrl = res;
this.editForm.image = res;
});
},
// 把图片转为base64编码
getBase64(file) {
return new Promise(function (resolve, reject) {
const reader = new FileReader();
let imgResult = '';
reader.readAsDataURL(file);
reader.onload = function () {
imgResult = reader.result;
};
reader.onerror = function (error) {
reject(error);
};
reader.onloadend = function () {
resolve(imgResult);
};
});
},
最后出来的效果就是这样的啦