参考:antd upload组件使用_ERRFTF的博客-CSDN博客
antd upload实例和一些解决问题的办法_热爱前端的小君同学的博客-CSDN博客
const [states, setStates] = useState<{
loading: boolean;
imageUrl: string | undefined;
}>({
loading: false,
imageUrl: ''
});
const getBase64 = (img: any, callback: (str: any) => void) => {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
};
组件的Upload的使用:
里面的属性
beforeUpload:这个属性就是上传的类型限制
//这个beforeUpload属性是限制类型,固定写法
const beforeUpload = (file:any) => {
console.log('file', file);
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJPG) {
message.error('只能上传JPG或PNG格式的图片文件!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
}
return isJPG && isLt2M;
}
customRequest: 作为自定义上传的方法与后端进行交互并可以传递额外的参数
const posterUploadFile = async (options: any) => {
// 创建一个空对象实例
const uploadData = new FormData();
// 调用append()方法来添加数据
uploadData.append('file', options.file);
uploadData.append('bizKey', type ? 'media' : 'news');
const res: any = await uploadImage(uploadData);
if (res) {
onChange?.(res.filePath);
setStates((states) => ({ ...states, loading: false, imageUrl: res.filePath || '' }));
} else {
message.error('长传失败');
setStates((states) => ({ ...states, loading: false }));
}
};
onchange:方法可以通过上传的状态对文件进行一些判断
handleChange = async(info) => {
if (info.file.status === 'uploading') {
this.setState({ loading: true });
return;
}
if (info.file.status === 'done') {
// Get this url from response in real world.
await this.getBase64(info.file.originFileObj, imageUrl =>
this.setState({
imageUrl,
loading: false,
fileList:info.fileList,
}),
);
}
};
或者
const handleChange = (info: UploadChangeParam<UploadFile<any>>) => {
if (info.file.status === 'uploading') {
setStates((states) => ({ ...states, loading: true }));
return;
}
if (info.file.status === 'done') {
// Get this url from response in real world.
getBase64(info.file.originFileObj, (imageUrl: string) => {
setStates({
imageUrl,
loading: false
});
});
}
};
组件
<Upload
disabled={disabled}
onChange={handleChange}
listType="picture-card"
beforeUpload={beforeUpload}
showUploadList={false}
className={classNames({ 'avatar-uploader': !type })}
customRequest={posterUploadFile}
>
<img />
</Upload>