提问人:yES-iAM 提问时间:11/12/2023 最后编辑:yES-iAM 更新时间:11/12/2023 访问量:48
Antd 表单:提交时上传文件 按钮 [关闭]
Antd form: upload file on submit button [closed]
问:
需要以下要求的代码:
- Antd 在提交按钮单击时使用表单上传文件。
- 添加文件验证。
- 只允许一个文件。
答:
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;
评论