react使用antd组件完成文件上传

这是一个使用React、Ant Design和Dva实现的头像上传组件的详细代码示例。组件限制了上传文件的类型为JPG/PNG,大小不超过5MB,并通过Ant Design的Upload组件进行文件上传,同时提供了图片预览功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 以上传头像为例(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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值