PdfUpload.tsx 1.89 KB
Newer Older
DarkForst's avatar
DarkForst committed
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
import React, {useState} from 'react';
import {Upload, message, Spin, Form} from 'antd';
import { _apiUrl_ } from '@/utils/common';

type PdfUploadProps = {
  onSave: (file: any[]) => void;
}

const PdfUpload: React.FC<PdfUploadProps> = props => {
  const [form] = Form.useForm()
  const { children, onSave } = props;
  const [loading, setLoading] = useState<boolean>(false)


  const action = `${_apiUrl_}/account-service/file/document`;

  const beforeUpdate = (file: any) => {
    // const isLt10M = file.size / (1024 * 1024) > 10;
    // if(isLt10M) message.error('文件大小不得超过10M');
    const isPdf = (file.type === 'application/pdf');
    if(!isPdf) message.error('只支持pdf格式');
    if (isPdf) setLoading(true)
    return isPdf
  }

  const handleChange = (info: any) => {
    const file = info.file;
    if (file?.status === 'done'){
      setLoading(false)
      if (!file.response.success) {
        message.error(file.response.message)
      }
      onSave?.(file)
    }
  };

  const options = {
    headers: {
      Authorization: `bearer ${localStorage.getItem("Authorization")}`
    },
    action,
    name: 'docFile',
    onChange: handleChange
  };

  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    const fileList = e?.fileList
    if (fileList && e?.file?.status === 'done') {
      return e?.fileList?.filter((item: any) => item?.response?.success || item?.url)
    }
    return e && e.fileList;
  };

  return (
    <Form form={form}>
      <Form.Item
        name="newList"
        valuePropName="fileList"
        getValueFromEvent={normFile}
        style={{marginBottom: 0}}
      >
        <Upload
          showUploadList={false}
          beforeUpload={ beforeUpdate }
          {...options}
        >
          <Spin size="small" spinning={loading || false}>{children}</Spin>
        </Upload>
      </Form.Item>
    </Form>

  );
}

export default PdfUpload;