ant-design Upload组件自定义上传

在使用ant-design进行表单开发(注册)的时候遇到需要包含图片数据的提交
但是由于是注册,java那边是先有提交的数据后生成新用户,注册时提交的数据没法找到对应的用户
因此没有开发图片的上传接口,前端的做法是保存用户注册的数据一次性提交给后端
由于没有上传接口也就没有action,改为是有用customRequest自定义上传

<Form.Item>
  <Form.Item
    name="certificationFiles"
    valuePropName="fileList"
    getValueFromEvent={normFile}
    noStyle
    rules={[
      { required: true, message: '请上传附件!' },
    ]}
  >
    <Upload
      listType="picture-card"
      customRequest={customRequest}
      maxCount={5}
      beforeUpload={beforeUpload}
      onPreview={handlePreview}
      style={{ backgroundColor: '#ECF2FF' }}
    >
      {uploadButton}
    Upload>
  Form.Item>
Form.Item>
const [imgList, setImgList] = useState([]);

// base64转Blob
const base64ToBlob = (code: string) => {
  const parts = code.split(';base64,');
  const contentType = parts[0].split(':')[1];
  const raw = window.atob(parts[1]);
  const rawLength = raw.length;
  const uInt8Array = new Uint8Array(rawLength);
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  return new Blob([uInt8Array], { type: contentType });
};

// 自定义上传逻辑
const customRequest = async (options: any) => {
  const { file, filename, data } = options;
  console.log(file, filename, data);

  const base64: any = await getBase64(file);
  const newImgList = [
    ...imgList,
    {
      uid: file.uid,
      name: file.name,
      status: 'done',
      url: URL.createObjectURL(base64ToBlob(base64)),
      lastModified: file.lastModified,
      lastModifiedDate: file.lastModifiedDate,
      originFileObj: file,
      percent: 100,
      thumbUrl: base64,
      type: file.type,
    },
  ];
  setImgList(newImgList);
  const fileList = registerForm.getFieldValue('certificationFiles');
  console.log(fileList);

  registerForm.setFieldsValue({ certificationFiles: newImgList });
};

这样registerForm.getFieldsValue()就能一次性拿到所有表单项的数据了

注意:

  1. 上面代码省略了beforeUploadgetBase64以及handlePreview函数,官方Upload组件例子里能找到。
  2. 即使是用了customRequestUpload组件的beforeUploadhandlePreview也依然生效。

你可能感兴趣的:(业务,ant-design,Upload,customRequest)