直接上代码:
<Upload className="avatar-uploader" showUploadList={false} accept='image/*' beforeUpload={this.beforeUpload}>
{base64
? <div>
<img alt="example" style={{ width: '88%' }} src={base64} />
</div>
: <div style={{ textAlign: 'center' }}>
<Icon type={isLoading ? 'loading' : 'plus' } />
<div className="ant-upload-text">上传</div>
</div>}
</Upload>
在beforeUpload事件中获取base64
beforeUpload = (file: any) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const base64Str = reader.result;
this.setState({ base64: base64Str })
resolve({ base64: base64Str, name: file.name });
};
reader.onerror = (error) => reject(error);
});
}