以上传头像为例(image文件 .png/.jpeg/.jpg)
import React from 'react';
import { withRouter } from 'dva/router';
import { Button, Form, Upload, Icon, message, Modal } from 'antd';
interface Props {
dispatch: any;
hospitalInformation: any;
form: any;
}
class hospitalInformation extends React.PureComponent<Props, any> {
constructor(props) {
super(props);
this.state = {
hospitalLogoPic: '',//头像路径 相对路径
filePath: '',//头像路径 绝对路径
editTF: false,//通过是否有id判断 保存POST还是编辑PUT
fileList: [],
previewImage: '',//图片路径
previewVisible: false,
}
}
beforeUpload = (file) => {//上传大小限制
const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
if (!isJpgOrPng) {
message.error('请选择JPG/PNG格式图片!!');
}
const isLt2M = file.size / 1024 / 1024 < 5;
if (!isLt2M) {
message.error('请选择小于5MB的图片!');
}
return isJpgOrPng && isLt2M;
}
upload = (info) => {
let formData = new FormData();
formData.append('files', info.file);
formData.append('user', JSON.parse(localStorage.getItem("userInfo")).username);
this.props.dispatch({//过接口上传至服务器
// type: 'hospitalInformation/batch',
payload: formData
}).then(res => {
this.setState({ isLoading: true })
// if (res.code == 200) {
message.success('上传成功!')
this.setState({
hospitalLogoPic: res.fileList[0].fileName,//相对地址(传参)
filePath: res.fileList[0].filePath,//绝对地址
})
// }
})
}
handleCancel = () => this.setState({ previewVisible: false });
handlePreview = () => this.setState({ previewVisible: true });
render() {
const { hospitalLogoPic, isLoading, filePath } = this.state
return (
<div className="hospitalInformation-page">
<div style={{ marginLeft: '30%', marginTop: '10%' }}>
<Form.Item label="" >
<Upload
className="avatar-uploader"
showUploadList={false}
accept='image/*'
beforeUpload={this.beforeUpload}
customRequest={this.upload}
>
{/* 上传后获得图片路径后显示 */}
{hospitalLogoPic && hospitalLogoPic.length > 0
? <img src={filePath ? filePath : `${hospitalLogoPic}`} alt="avatar" style={{ width: 450, height: 300 }} />
: (
<div>
<Icon type={isLoading ? 'loading' : 'plus'} />
<div className="ant-upload-text">Upload</div>
<img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
</div>
)}
</Upload>
{/* 用于点击弹出图片查看框 */}
<Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel}>
<img alt="example" style={{ width: '100%' }} src={filePath} />
</Modal>
</Form.Item>
</div>
<div style={{ marginLeft: '30%', marginTop: '25%' }}>
<div style={{ color: '#C6241D' }}>注:点击图片重新上传</div>
<b>只能上传jpeg/png文件,且不超过5MB</b>
<Button onClick={this.handlePreview} type="primary" icon="search" style={{ display: filePath ? '' : 'none', marginLeft: 40 }}>查看</Button>
</div>
</div>
)
}
}
export default withRouter(Form.create()(hospitalInformation));