组件引入
import { Upload } from "antd";
import { LoadingOutlined } from "@ant-design/icons";
import { getFileWidthAndHeight } from "@/util";
//导入检测图片尺寸代码
export const getFileWidthAndHeight = (file, initwidth, initheight) => {
return new Promise((resolve, reject) => {
let width = initwidth;
let height = initheight;
let _URL = window.URL || window.webkitURL;
let img = new Image();
img.src = _URL.createObjectURL(file);
img.onload = function () {
if (img.width > width || img.height > height) {
errorNotification(`上传尺寸最大${initwidth}px * ${initheight}px!`);
reject();
} else {
resolve();
}
};
});
};
上传前检测
const [loadingcard, setloadingcard] = useState(false); //loading
const beforeUpload = (file) => {
const isJpgOrPng =
file.type === "image/jpeg" ||
file.type === "image/png" ||
file.type === "image/bmp";
return isJpgOrPng;
//临时关闭校验
if (!isJpgOrPng) {
errorNotification("你必须上传 JPG/PNG 文件!");
return false;
}
const isLt2M = file.size / 1024 / 1024 < 3;
if (!isLt2M) {
errorNotification("图像必须小于3MB!");
return false;
}
//检测尺寸
return getFileWidthAndHeight(file, 500, 500);
};
const uploadCard = (info) => {
if (info.file.status === "uploading") {
setloadingcard(true);
return;
}
if (info.file.status === "done") {
const { code, data } = info.file.response;
setloadingcard(false);
if (code === 200) {
setChannelCard(data.url);
}
}
};
组件upload使用
const uploadButton = (
<div>
{loadingcard ? (
<LoadingOutlined />
) : (
<div className="uploadPictures">
<div className="pic_bg"> </div>
<div className="u_p">
<img
className="icon"
src={icon_zlgl_zx}
width="32"
height="26"
alt=""
/>
<span className="text">点击上传身份证人像面</span>
</div>
</div>
)}
</div>
);
<Upload
name="file"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
beforeUpload={beforeUpload}
onChange={uploadCard}
action={uploadImgUrl}
headers={{
Authorization: getToken(),
}}
>
{imageUrl ? (
<div className="auth_upload_rebox">
<img
src={imageUrl}
alt="avatar"
className="upIdentity"
/>
<p className="upload_reload">重新上传</p>
</div>
) : (
uploadButton
)}
</Upload>