VUE element-ui之上传身份证照片正反面详细代码
步骤:
定义上传组件:
<el-col :lg="6"> <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false" :on-change="changePictureUploadIDFront"> <img v-if="imageUrlFront" :src="imageUrlFront" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon" /> </el-upload> <div class="el-upload__tip">身份证正面</div> </el-col> data() { retrun { imageUrlFront: } }
定义方法:
// 文件发生变化时 changePictureUploadIDFront(file, fileList) { console.log(`------`, file) const isJPG = file.raw.type === image/jpeg const isPNG = file.raw.type === image/png const isLt2M = file.raw.size / 1024 / 1024 < 2 if (file.raw) { if (isJPG || isPNG) { const fileFormData = new FormData() fileFormData.append(files, file.raw) addIdCard(fileFormData).then(res => { //调用上传接口 if (res) { this.imageUrlFront = URL.createObjectURL(file.raw)//接口调用成功后赋值src this.$message({ message: 恭喜你,上传成功!, type: success }) } }) this.imageUrlFront = URL.createObjectURL(file.raw) } else { this.$message.error(上传图片只能是 JPG或PNG 格式!) } } if (!isLt2M) { this.$message.error(上传图片大小不能超过 2MB!) } // 返回图是jpg或png格式并且大小不超过2MB return (isJPG || isPNG) && isLt2M }
注:方法步骤一目了然,懂得自然懂。 看效果: