项目中有一个需求,要上传轮播图,且有尺寸要求,所以就需要在上传图片的时候进行尺寸限制,使用了Upload组件,需要在组件的beforeUpload方法中进行限制。
定义一个上传前的方法,并且添加一个图片尺寸获取的方法:
如果尺寸不符合要求,validateImageSize方法会返回false,如果尺寸符合就会返回true
// Carousel upload handle
const carouselUpload: any = async (file: any) => {
console.log('only limit 750x420', file)
const limitSize = await validateImageSize(file)
if (!limitSize) {
console.log('only limit error', file)
message.error('图片尺寸不符合要求,请重新上传')
}
return limitSize || Upload.LIST_IGNORE
}
const validateImageSize = (file: any) => {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = (e: any) => {
const image = new Image()
image.onload = function () {
const { width, height } = this as any
console.log('image size is width height', width, height)
if (width === 150 && height === 150) {
resolve(true)
} else {
resolve(false)
}
}
image.onerror = reject
image.src = e.target.result
}
reader.onerror = reject
reader.readAsDataURL(file)
})
}
组件中添加使用:
<Upload
action="https://dev.hado-official.cn/service_api/file_upload"
accept="image/*"
fileList={fileList}
maxCount={3}
beforeUpload={carouselUpload}
onChange={onChange}
onPreview={onPreview}
>
{fileList.length < 5 && (
<div className="uploadBox">
<span className="uploadBtn">点击上传</span>
<span className="uploadTips">
最多3张,单张图片不超过10MB,尺寸750*420px,支持jpg/png/bmp格式
</span>
</div>
)}
</Upload>