50字范文,内容丰富有趣,生活中的好帮手!
50字范文 > react+ant 图片 upload 上传文件大小和尺寸 验证

react+ant 图片 upload 上传文件大小和尺寸 验证

时间:2023-10-14 04:42:04

相关推荐

react+ant 图片 upload 上传文件大小和尺寸 验证

组件引入

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); //loadingconst 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"><imgclassName="icon"src={icon_zlgl_zx}width="32"height="26"alt=""/><span className="text">点击上传身份证人像面</span></div></div>)}</div>);<Uploadname="file"listType="picture-card"className="avatar-uploader"showUploadList={false}beforeUpload={beforeUpload}onChange={uploadCard}action={uploadImgUrl}headers={{Authorization: getToken(),}}>{imageUrl ? (<div className="auth_upload_rebox"><imgsrc={imageUrl}alt="avatar"className="upIdentity"/><p className="upload_reload">重新上传</p></div>) : (uploadButton)}</Upload>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。