【代码】AntDesign的Upload组件实现自定义图片上传

前言

AntDesign的Upload组件实现自定义图片上传

源代码

  • 通过beforeUpload事件拦截默认的图片上传操作,获取图片Base并实现自定义图片上传
index.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { Upload } from 'antd';

const Index = () => {

function handleBeforeUpload(file) {
const reader = new FileReader();
reader.onload = (e) => {
// 获取图片Base64
const base64String = e.target.result;

...

};
reader.readAsDataURL(file);

// 阻止默认上传行为
return false;
}

return (
<Upload listType="picture-card" beforeUpload={handleBeforeUpload}>
<button style={{ color: 'inherit', cursor: 'inherit', border: 0, background: 'none' }} type="button">
<PlusOutlined />
</button>
</Upload>
);
};

export default Index;

完成