private beforeAvatarUpload(file: any) {
// 上传图片校验
const self = this;
const isLt2M = file.size / 1024 / 1024 < 10;
const testmsg = file.name.substring(file.name.lastIndexOf('.') + 1);
const imgarr = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'pdf', 'JPG', 'JPEG', 'PNG', 'GIF', 'BMP', 'PDF'];
if (imgarr.indexOf(testmsg) === -1) {
(this as any).$message.error('上传图片格式不正确,请重新上传');
return false;
}
if (!isLt2M) {
(this as any).$message({
message: '上传图片大小不能超过 10MB!',
type: 'warning',
});
}
const imgBase64: any = '';
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event: any) => {
const imgUrl = event.target.result;
file.url = imgUrl; // 获取到base64格式图片
file.Imgname = file.name;
(self as any).filsData.push(file);
};
return false;
}
private uploadSuccess(response: any, file: any, fileList: any) {
console.log(file);
}
private handleRemove(file: any) {
const index = this.filsData.indexOf(file);
if (index !== -1) {
this.filsData.splice(index, 1);
}
}
private handlePictureCardPreview(file: any) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
}
element 上传功能 页面编写
<el-upload
class="upload-demo"
action=""
list-type="picture"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-success="uploadSuccess"
:before-upload="beforeAvatarUpload"
:file-list="filsData"
>
<i class="el-icon-plus"></i>
</el-upload>
<div slot="tip" class="el-upload__tip">只能上传图片文件,且不超过10M</div>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
代码逻辑