Antd 表单:提交时上传文件 按钮 [关闭]

Antd form: upload file on submit button [closed]

提问人:yES-iAM 提问时间:11/12/2023 最后编辑:yES-iAM 更新时间:11/12/2023 访问量:48

问:


想改进这个问题吗?通过编辑这篇文章添加详细信息并澄清问题。

8天前关闭。

需要以下要求的代码:

  • Antd 在提交按钮单击时使用表单上传文件。
  • 添加文件验证。
  • 只允许一个文件。
JavaScript 表单 antd

评论

0赞 mplungjan 11/12/2023
请写一个适当的问题。
0赞 Community 11/12/2023
请澄清您的具体问题或提供其他详细信息以准确说明您的需求。正如目前所写的那样,很难确切地说出你在问什么。

答:

0赞 yES-iAM 11/12/2023 #1

Antd 版本 5.11.1

import React, { useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button, message, Upload, Form } from 'antd';

const App = () => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);

  const handleUpload = () => {
    form.validateFields().then(() => {
      const formData = new FormData();
      fileList.forEach((file) => {
        formData.append('files[]', file);
      });
      setUploading(true);

      fetch('https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188', {
        method: 'POST',
        body: formData,
      })
        .then((res) => res.json())
        .then(() => {
          setFileList([]);
          form.resetFields(); // Reset the form after successful upload
          message.success('Upload successful.');
        })
        .catch(() => {
          message.error('Upload failed.');
        })
        .finally(() => {
          setUploading(false);
        });
    });
  };

  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const props = {
    beforeUpload: (file) => {
      const isPDF = file.type === 'application/pdf';
      const isLt100M = file.size / 1024 / 1024 < 1;

      if (!isPDF) {
        message.error('You can only upload PDF files!');
        return Upload.LIST_IGNORE;
      } else if (!isLt100M) {
        message.error('File must be smaller than 1MB!');
        return Upload.LIST_IGNORE;
      } else {
        setFileList([file]);
      }
      return false;
    },
    fileList,
    maxCount: 1,
    accept: ".pdf"
  };

  return (
    <Form form={form} onFinish={handleUpload}>
      <Form.Item
        name="fileList"
        valuePropName="fileList"
        getValueFromEvent={normFile}
        rules={[
          {
            required: true,
            message: 'Please upload a file',
          },
        ]}>
        <Upload {...props}>
          <Button icon={<UploadOutlined />}>Select File</Button>
        </Upload>
      </Form.Item>
      <Button
        type="primary"
        htmlType="submit"
        //disabled={fileList.length === 0}
        loading={uploading}
        style={{ marginTop: 16 }}
      >
        {uploading ? 'Uploading' : 'Start Upload'}
      </Button>
    </Form>
  );
};

export default App;