ant design upload 校验上传图片时,可以固定输出图片的尺寸,调用beforeUpload方法,在上传前运用canvas重新绘制,并返回promise对象
<Upload
name="file"
listType="picture-card"
className={cls.upImg}
showUploadList={false}
headers={{ Authorization }}
action={''}
beforeUpload={beforeUploadLogo} //上传前调用的方法
fileList={brandLogoImageList}
onChange={changePicture}
onPreview={handlePreviewModelImage}>
{brandLogoImage ? (
<img
src={brandLogoImage}
alt="avatar"
style={{ width: '100%', height: '100%' }}
/>
) : (
uploadButtonLogo
)}
</Upload>
调用beforeUpload方法
let beforeUploadLogo = (file: { type: string; size: number }) => {
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!')
}
if (isJpgOrPng && isLt2M) {
//这里调用checkImageWH方法,返回一个promise对象
return checkImageWH(file, 600, 600)
} else {
//图片类型,大小检验不通过时,返回 Upload.LIST_IGNORE,阻止文件进入上传列表
return Upload.LIST_IGNORE
}
}
图片转换
let checkImageWH = (file: any, width: number, height: number) => {
return new Promise((resolve) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
const img = document.createElement('img')
img.src = reader.result as string
img.onload = () => {
const canvas = document.createElement('canvas')
//这里使用变量固定宽高
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')!
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(img, 0, 0, width, height)
canvas.toBlob((result) => resolve(result as any))
}
}
})
}
注意:重新定义file文件,返回的值必须是promise对象,不要在beforeUpload方法上面运用async await,会导致出错