Reputation: 51
Even though the file is uploaded antd Form.item rules throws error. Which mean it's not getting the value from Upload to the form.item how should i solve this error. Note im using antd latest version 4.x in which getFieldDecorator has been deprecated. And i also want to upload file manually.
import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Alert, Upload } from 'antd';
import { UserOutlined, LockOutlined, UploadOutlined } from '@ant-design/icons';
import styles from './test1.module.css';
const Test1 = () => {
const [form] = Form.useForm();
const [state, setState] = useState({
fileList: [
{
thumbUrl:
'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
],
});
const handleChange = (info) => {
console.log(info);
let fileList = [...info.fileList];
// 1. Limit the number of uploaded files
// Only to show two recent uploaded files, and old ones will be replaced by the new
fileList = fileList.slice(-1);
setState({ fileList: fileList });
};
const onFinish = (values) => {
console.log(form.getFieldsValue());
};
return (
<div className={styles.login_page}>
<Form
name='normal_login'
className={styles.form}
form={form}
onFinish={onFinish}
>
<Form.Item
name='email'
rules={[
{
required: true,
message: 'Please input your Email!',
},
]}
>
<Input
prefix={<UserOutlined className='site-form-item-icon' />}
placeholder='Email'
/>
</Form.Item>
<Form.Item
name='password'
rules={[
{
required: true,
message: 'Please input your Password!',
},
]}
>
<Input
prefix={<LockOutlined className='site-form-item-icon' />}
type='password'
placeholder='Password'
/>
</Form.Item>
<Form.Item
name='image'
rules={[
{
required: true,
message: 'input Image',
},
]}
>
<Upload
beforeUpload={(file) => {
// console.log(file);
return false;
}}
onChange={handleChange}
multiple={false}
listType='picture'
defaultFileList={state.fileList}
>
<Button icon={<UploadOutlined />}>Click to Upload</Button>
</Upload>
</Form.Item>
<Form.Item>
<Button type='primary' htmlType='submit'>
Log in
</Button>
</Form.Item>
</Form>
</div>
);
};
export default Test1;
Is there any way i can bind the onChange event listener of Upload with form.Item
Upvotes: 5
Views: 23618
Reputation: 411
Use prop getValueFromEvent
in Form.Item
and pass the function returning a file object.
const getFile = (e) => {
console.log('Upload event:', e);
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
};
and Form.Item
for image will be like this
<Form.Item name='image' getValueFromEvent={getFile}>
<Upload >
....
</Upload>
</Form.Item>
and you can get all form values in onFinish
const onFinish = (values) => {
console.log(values)
}
for further refer this
Upvotes: 14
Reputation: 51
You can use maxCount prop of Upload component. It will limit the upload file to specified value.
reference: Upload Component
Upvotes: 3