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