upload.tsx 2.05 KB
import { postOrderErpTicketsUpload } from '@/services';
import { UploadOutlined } from '@ant-design/icons';
import ProCard from '@ant-design/pro-card';
import { Button, Form, Upload, message } from 'antd';
import { useState } from 'react';

type File = {
  uid: string;
  name: string;
  url: string;
};

const MyComponent = ({ form, isEditMode }) => {
  const [fileList, setFileList] = useState<File[]>([]);

  const handleUploadChange = async (info) => {
    setFileList(info.fileList);

    if (
      info.file.status === 'uploading' &&
      info.file.originFileObj instanceof File
    ) {
      const formData = new FormData();
      formData.append('file', info.file.originFileObj);

      const res = await postOrderErpTicketsUpload({
        data: formData,
        headers: { 'Content-Type': 'multipart/form-data' },
      });

      if (res.message === '成功') {
        message.success('上传成功');
        setFileList([
          {
            uid: info.file.uid,
            name: info.file.name,
            url: res.data,
          },
        ]);
        form.setFieldsValue({ annexUrl: res.data, annexName: info.file.name });
      }
    }
  };

  const uploadProps = {
    onChange: handleUploadChange,
    fileList: fileList,
    onRemove: () => {
      setFileList([]);
      form.setFieldsValue({ annexUrl: null, annexName: null });
    },
  };

  const shouldShowUploadButton = fileList.length === 0;

  return (
    <ProCard>
      <Form.Item label="附件" name="annexUrl">
        {isEditMode ? (
          <Upload {...uploadProps}>
            {shouldShowUploadButton && (
              <Button icon={<UploadOutlined />}>上传附件</Button>
            )}
          </Upload>
        ) : form.getFieldValue('annexUrl') ? (
          <a
            href={form.getFieldValue('annexUrl')}
            target="_blank"
            rel="noopener noreferrer"
          >
            {form.getFieldValue('annexName') || '附件'}
          </a>
        ) : (
          <span>无附件</span>
        )}
      </Form.Item>
    </ProCard>
  );
};

export default MyComponent;