2021-08-17 10:46:28 +05:00
|
|
|
import { Form, Upload, Button} from 'antd'
|
|
|
|
import { UploadOutlined} from '@ant-design/icons'
|
|
|
|
import { useState } from 'react'
|
|
|
|
import { upload } from './factory'
|
|
|
|
|
2021-08-17 13:01:13 +05:00
|
|
|
export default function UploadForm({url, onUploadStart, onUploadComplete, onUploadError}) {
|
2021-08-17 10:46:28 +05:00
|
|
|
const [isSubmitButtonEnabled, setSubmitButtonEnabled] = useState(false)
|
|
|
|
const [form] = Form.useForm();
|
|
|
|
|
|
|
|
const handleFileSend = async (values) => {
|
|
|
|
if(onUploadStart)
|
|
|
|
onUploadStart()
|
|
|
|
try {
|
|
|
|
const values = await form.validateFields();
|
|
|
|
const formData = new FormData()
|
2021-08-17 13:01:13 +05:00
|
|
|
values.file.fileList.forEach((val) => {
|
2021-08-17 10:46:28 +05:00
|
|
|
formData.append("files", val.originFileObj);
|
|
|
|
});
|
|
|
|
await upload(url, formData)
|
|
|
|
} catch(error) {
|
|
|
|
if(onUploadError)
|
|
|
|
onUploadError(error)
|
|
|
|
} finally {
|
|
|
|
form.resetFields()
|
|
|
|
if(onUploadComplete)
|
|
|
|
onUploadComplete()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return(
|
|
|
|
<Form
|
|
|
|
form={form}
|
|
|
|
onFinish={handleFileSend}
|
|
|
|
style={{display: 'flex'}}>
|
|
|
|
<Form.Item
|
|
|
|
name="file"
|
|
|
|
style={{marginBottom: 0}}
|
|
|
|
rules={[{ required: true, message: 'Выберите файл' }]}>
|
|
|
|
<Upload
|
|
|
|
name ="file"
|
|
|
|
onChange={(props) => setSubmitButtonEnabled(props.fileList.length > 0)}>
|
|
|
|
<Button icon={<UploadOutlined/>}>Загрузить файл</Button>
|
|
|
|
</Upload>
|
|
|
|
</Form.Item>
|
|
|
|
<Form.Item style={{marginBottom: 0}}>
|
|
|
|
<Button
|
|
|
|
type="primary"
|
|
|
|
htmlType="submit"
|
|
|
|
disabled={!isSubmitButtonEnabled}
|
|
|
|
style={{marginLeft: '10px', display:isSubmitButtonEnabled?'':'none'}}>
|
|
|
|
Отправить
|
|
|
|
</Button>
|
|
|
|
</Form.Item>
|
|
|
|
</Form>
|
|
|
|
)
|
|
|
|
}
|