antd upload文件格式 大小 尺寸校验

通过beforeUpload 校验
  • 上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。支持返回一个 Promise 对象,Promise 对象 reject 时则停止上传,resolve 时开始上传( resolve 传入 File 或 Blob 对象则上传 resolve 传入对象);也可以返回 Upload.LIST_IGNORE,此时列表中将不展示此文件。 注意:IE9 不支持该方法
  • beforeUpload 返回 false 或 Promise.reject 时,只用于拦截上传行为,不会阻止文件进入上传列表(原因)。如果需要阻止列表展现,可以通过返回 Upload.LIST_IGNORE 实现。
import { Button, message, Upload } from 'antd'
const Index= () => {// 检测尺寸const isSize = (file: File, width: number, height: number) => {return new Promise<void>((resolve, reject) => {const _URL = window.URL || window.webkitURLconst img = new Image()img.onload = () => {_URL.revokeObjectURL(img.src)const valid = img.width === width && img.height === heightvalid ? resolve() : reject()}img.src = _URL.createObjectURL(file)}).then(() => {return file}).catch(() => {message.error(`只能上传尺寸为${width}*${height}`)return false || Upload.LIST_IGNORE // 必须要返回 promiseRusule 为'Upload.LIST_IGNORE' 阻止列表展现})} const detailUploadProps: UploadProps = {name: 'file',beforeUpload: (file: any) => {const isJpgOrPng =file.type === 'image/jpeg' ||file.type === 'image/png' ||file.type === 'image/jpg' ||file.type === 'image/bmp'if (!isJpgOrPng) {message.error('仅支持格式为png、jpg、jpeg、bmp!')return isJpgOrPng || Upload.LIST_IGNORE}if (file.size >> 20) {message.error('大小不超过2MB!')return false || Upload.LIST_IGNORE}return isSize(file, 670, 335) 
// return 接受isSize 返回的 Upload.LIST_IGNORE},onChange(info) {const { status } = info.fileif (status === 'done') {if (!info.file.response.isSuccess) {message.error(`${info.file.name} ${info.file.response.message}`)return}message.success(`${info.file.name} 文件上传成功.`)} else if (status === 'error') {message.error(`${info.file.name} 文件上传失败.`)}}}return (<Upload{...detailUploadProps}><Button>上传文件</Button></Upload>)
}export default Index


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部