asb_cloud_front/src/components/UploadForm.jsx

62 lines
1.8 KiB
React
Raw Normal View History

import { memo, useState } from 'react'
2021-08-17 16:46:46 +05:00
import { Upload, Button } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
2021-08-17 10:46:28 +05:00
import { upload } from './factory'
2021-10-11 13:41:54 +05:00
import { ErrorFetch } from './ErrorFetch'
2021-08-17 10:46:28 +05:00
export const UploadForm = memo(({ url, disabled, accept, style, formData, onUploadStart, onUploadSuccess, onUploadComplete, onUploadError }) => {
2021-08-17 16:46:46 +05:00
const [fileList, setfileList] = useState([])
2021-08-17 10:46:28 +05:00
2021-10-11 13:41:54 +05:00
const handleFileSend = async () => {
onUploadStart?.()
2021-08-17 10:46:28 +05:00
try {
2021-10-11 13:41:54 +05:00
const formDataLocal = new FormData()
fileList.forEach((val) => formDataLocal.append('files', val.originFileObj))
2021-10-11 13:41:54 +05:00
if(formData)
for(const propName in formData)
2021-10-11 13:41:54 +05:00
formDataLocal.append(propName, formData[propName])
2021-10-11 13:41:54 +05:00
const response = await upload(url, formDataLocal)
if (!response.ok) {
const errorText = await response.text()
2021-10-11 13:41:54 +05:00
const error = new ErrorFetch(response.status, errorText)
throw error
} else {
onUploadSuccess?.()
2021-10-11 13:41:54 +05:00
}
2021-08-17 10:46:28 +05:00
} catch(error) {
if(process.env.NODE_ENV === 'development')
console.error(error)
onUploadError?.(error)
2021-08-17 10:46:28 +05:00
} finally {
2021-08-17 16:46:46 +05:00
setfileList([])
onUploadComplete?.()
2021-08-17 10:46:28 +05:00
}
}
2021-08-17 16:46:46 +05:00
const isSendButtonEnabled = fileList.length > 0
2021-08-17 10:46:28 +05:00
return(
<div style={{ display: 'flex', ...style }}>
<Upload
name={'file'}
accept={accept}
disabled={disabled}
fileList={fileList}
onChange={(props) => setfileList(props.fileList)}
>
<Button disabled={disabled} icon={<UploadOutlined/>}>Загрузить файл</Button>
2021-08-17 16:46:46 +05:00
</Upload>
<Button
type={'primary'}
onClick={handleFileSend}
2021-08-17 16:46:46 +05:00
disabled={!isSendButtonEnabled}
style={{ marginLeft: '10px', display: isSendButtonEnabled ? '' : 'none' }}
>
2021-08-17 16:46:46 +05:00
Отправить
</Button>
</div>
2021-08-17 10:46:28 +05:00
)
})