图片宽高校验方法:
// 上传图片尺寸限制 const checkIconWH = (file: any) => { return new Promise<void>(function (resolve, reject) { const fileReader = new FileReader(); fileReader.onload = (e) => { const image = new Image(); image.onload = function () { if (image.width !== 512 && image.height !== 512) { reject(); } else { resolve(); } }; image.onerror = reject; image.src = e?.target?.result && isString(e?.target?.result) ? e?.target?.result : ''; }; fileReader.readAsDataURL(file); }); };
视频宽高校验方法:
// 上传mp4尺寸限制 const checkVideoWH = (file: any, width: number, height: number) => { return new Promise<void>(function (resolve, reject) { const url = URL.createObjectURL(file); const video = document.createElement('video'); video.onloadedmetadata = () => { URL.revokeObjectURL(url); console.log(video.videoWidth, video.videoHeight) if (video.videoWidth < width || video.videoHeight < height) { reject() } else { resolve() } } video.src = url; video.load(); }); };
校验使用(在上传之前的beforeUpload方法中使用):
/** * 上传请求 * @param {object} file - 上传的文件 * @param {object} item - 上传的信息 * @param {string} type - 上传的类型 */ const upLoad = async (file: RcFile, item: PropsConfig, type?: string) => { let canContinue = true; //如果是icon,检测尺寸 if (item.type === 'icon') { await checkIconWH(file) .then(() => { canContinue = true; }) .catch(() => { canContinue = false; message.error('ICON需为512X512px,PNG格式的图片,请确认后重新上传'); return; }); } //如果是mp4,检测尺寸 if (item.type === 'mp4' && fileWidth && fileHeight) { await checkVideoWH(file, fileWidth, fileHeight) .then(() => { canContinue = true; }) .catch(() => { canContinue = false; message.error(fileCheckMsg || '文件校验失败'); return; }); } //如果是mp4且需要检测大小(fileSize单位是MB) if (item.type === 'mp4' && fileSize) { console.log(file, fileSize) if (file.size / 1024 / 1024 > fileSize) { canContinue = false; message.error(fileCheckMsg || '文件校验失败'); return; } canContinue = true; } if (!canContinue) return; ……………省略剩余代码……………
标签:const,宽高,upload,react,canContinue,video,file,校验,上传 From: https://www.cnblogs.com/nangras/p/16619680.html