介绍
我们经常会遇到,需要上传固定尺寸图片的场景,比如更换头像图片等。这时就需要先对图片进行裁切,Ant Desgin 默认并没有提供这样的功能。
antd-img-crop 是一个用于包装 Ant Design Upload 的组件,可实现在上传前,先对图片进行裁切,然后上传裁切后的图片。
使用
import React from 'react'
import { Upload, message, Button } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import ImgCrop from 'antd-img-crop'
function PicUpLoad({ actionUrl, onChange, aspect = '1/1', size = 0.5, value, num = 1 }) {
const beforeUpload = (file) => {
const isLt = file.size / 1024 / 1024 < size
return new Promise((resolve, reject) => {
if (!isLt) {
message.warning(`请上传小于${size}M的图片!`)
// eslint-disable-next-line prefer-promise-reject-errors
reject()
} else {
resolve()
}
})
}
return (
<ImgCrop rotate aspect={aspect}>
<Upload
name="commonFile"
accept=".png,.jpg,.jpeg"
listType="picture"
fileList={value}
action={actionUrl}
beforeUpload={beforeUpload}
onChange={(e) => onChange(e)}
maxCount={num}
withCredentials
>
<Button icon={<UploadOutlined />}>上传</Button>
</Upload>
</ImgCrop>
)
}
export default PicUpLoad