payWayUpload.tsx 2.51 KB
import { postOrderErpOrderStagesUpload } from '@/services/request';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, Upload, message } from 'antd';
import { RcFile } from 'antd/es/upload';
import React, { useEffect } from 'react';

const App: React.FC = ({ natureModel, setCurryFile }) => {
  const [fileList, setFileList] = React.useState([{}]);
  useEffect(() => {
    if (natureModel.fileUrl !== undefined && natureModel.fileUrl !== null) {
      setFileList([{ name: natureModel.fileName, url: natureModel.fileUrl }]);
    }
  }, []);

  const handleUploadChange = (value) => {
    setFileList(value.fileList);
    setCurryFile({
      id: natureModel.id,
      name: null,
      url: null,
    });
    if (
      value.fileList.length !== 0 &&
      value.fileList[0].status === 'uploading'
    ) {
      (async () => {
        if (!(value.fileList[0].originFileObj instanceof File)) {
          return false;
        } else {
          const formData = new FormData();
          formData.append('file', value.fileList[0].originFileObj as RcFile);
          const res = await postOrderErpOrderStagesUpload({
            data: formData,
            headers: {
              'Content-Type': 'multipart/form-data',
            },
          });
          if (res) {
            message.success('提交成功');

            setCurryFile({
              id: natureModel.id,
              name: value.fileList[0].originFileObj.name,
              url: res.data,
            });
            setFileList([
              {
                id: value.fileList[0].originFileObj.uid,
                name: value.fileList[0].originFileObj.name,
                url: res.data,
              },
            ]);
            return (
              <a href={res.data} target="_blank" rel="noopener noreferrer">
                {value.fileList[0].originFileObj.name}
              </a>
            );
          }
        }
      })();
    }
  };

  const props: UploadProps = {
    onChange(value) {
      handleUploadChange(value);
    },
  };

  const shouldShowUploadButton =
    fileList.length !== 1 || fileList[0].url === undefined;

  return (
    <Upload
      {...props}
      fileList={fileList.filter(
        (item) => item.url !== undefined && item.url !== null,
      )}
    >
      {shouldShowUploadButton && (
        <Button icon={<UploadOutlined />}>上传</Button>
      )}
    </Upload>
  );
};

export default App;

{
  /* {!shouldShowUploadButton && <a href={fileList[0].url}>{fileList[0].name}</a>} */
}