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

 以上传头像为例(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 {
  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 (
      
{/* 上传后获得图片路径后显示 */} {hospitalLogoPic && hospitalLogoPic.length > 0 ? avatar : (
Upload
example
)}
{/* 用于点击弹出图片查看框 */} example
注:点击图片重新上传
只能上传jpeg/png文件,且不超过5MB
) } } export default withRouter(Form.create()(hospitalInformation));

你可能感兴趣的:(react,react.js,javascript,前端)