使用antd组件库里的 a-upload 上传图片
template代码:
<a-upload
name="idCardzm"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
:before-upload="beforeUpload"
:customRequest="handleChange"
>
<img class="img" v-if="formTableData.idCardzm" :src="formTableData.idCardzm" alt="身份证头像面" />
<div v-else>
<loading-outlined v-if="loading"></loading-outlined>
<plus-outlined v-else></plus-outlined>
<div class="ant-upload-text">身份证头像面</div>
</div>
</a-upload>
<a-upload
name="idCardbm"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
:before-upload="beforeUpload"
:customRequest="handleChange"
>
<img class="img" v-if="formTableData.idCardbm" :src="formTableData.idCardbm" alt="身份证国徽面" />
<div v-else>
<loading-outlined v-if="loading"></loading-outlined>
<plus-outlined v-else></plus-outlined>
<div class="ant-upload-text">身份证国徽面</div>
</div>
</a-upload>
<a-upload
name="idCardsc"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
:before-upload="beforeUpload"
:customRequest="handleChange"
>
<img class="img" v-if="formTableData.idCardsc" :src="formTableData.idCardsc" alt="手持身份证照片" />
<div v-else>
<loading-outlined v-if="loading"></loading-outlined>
<plus-outlined v-else></plus-outlined>
<div class="ant-upload-text">手持身份证照片</div>
</div>
</a-upload>
a-upload 属性解析
- name:发到后台的文件参数名 (常用于同一页面需要写多个上传图片时)
- list-type:上传列表的内建样式,支持三种基本样式 text, picture 和 picture-card
- show-upload-list:是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon, showRemoveIcon 和 showDownloadIcon
- before-upload:上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。支持返回一个 Promise 对象,Promise 对象 reject 时则停止上传,resolve 时开始上传( resolve 传入 File 或 Blob 对象则上传 resolve 传入对象)。
- customRequest:通过覆盖默认的上传行为,可以自定义自己的上传实现 (最常用)
script 代码:
// 初始值
let formTableData = ref({
idCardzm: '',
idCardbm: '',
idCardsc: '',
});
//主要用图片上传前的限制操作(非必写)
const beforeUpload = file => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('只能上传JPG、PNG格式图片!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片尺寸不能超过2MB!');
}
return isJpgOrPng && isLt2M;
};
// 图片上传
const loading = ref(false);
const handleChange = async (info) => {
loading.value=true
//info.filename的值与a-upload里的name对应,这样就可以多个位置都使用同一方法
const idCard = info.filename
const FormDatas = new FormData();
FormDatas.append("multipartFile", info.file);
//api.upload_uploadImages后端给的图片上传解析的接口方法
const data = (await api.upload_uploadImages(FormDatas)).data
loading.value=false
//将后端返回的图片路径值赋给所在图片所绑定的值
formTableData.value[idCard] = data
};
style代码:
.avatar-uploader>.ant-upload {
width: 128px;
height: 128px;
}
.img {
max-width: 100%;
max-height: 100%;
}
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
margin-top: 8px;
color: #666;
}
直接复制代码即可,回头补充删除图片事件