使用antd组件库里的 a-upload 上传图片
template代码:
<a-form-item class="image-upload">
<a-upload
name="idCardzm"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
:before-upload="beforeUpload"
:customRequest="handleChange"
@mouseenter="handleMouseEnter"
@mouseleave="handleMouseLeave"
>
<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>
<close-outlined
v-if="showDeleteIcon && formTableData.idCardzm"
class="delete-icon"
type="close-circle"
@click.stop="deleteImage('idCardzm')"
></close-outlined>
</a-upload>
</a-form-item>
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 代码:
import {
PlusOutlined,
LoadingOutlined,
CloseOutlined,
} from '@ant-design/icons-vue';
// 初始值
let formTableData = ref({
idCardzm: ''
});
//主要用图片上传前的限制操作(非必写)
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
};
//控制删除icon
const showDeleteIcon = ref(false)
//鼠标悬停事件
const handleMouseEnter=()=> {
showDeleteIcon.value = true;
}
//鼠标离开事件
const handleMouseLeave=()=> {
showDeleteIcon.value = false;
}
//删除当前图片
const deleteImage =(idCard)=> {
formTableData.value[idCard]= ''; // 清除图片数据
showDeleteIcon.value = false; // 隐藏删除图标
}
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;
}
.image-upload {
position: relative;
}
.delete-icon {
position: absolute;
top: 5px;
right: 10px;
color: black;
font-size: 12px;
cursor: pointer;
}