项目中有一个需求,要上传轮播图,且有尺寸要求,所以就需要在上传图片的时候进行尺寸限制,使用了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) }) }
组件中添加使用:
{fileList.length