I’m trying to submit a form with an image, using AntDesign and the antd-img-crop
for cropping the image before uploading, in React.js. However, when i’m trying to send the form values to the server, in the submit function, the file is undefined
. How to fix it ?
Form item for the image:
<Form.Item name="file" label="Category Image" valuePropName="file">
<ImgCrop rotationSlider>
<Upload
accept={'.jpg, .jpeg, .png'}
name="avatar"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
customRequest={this.customRequest}
>
{this.state.selectedData.image != '' ? (
<img
src={this.state.selectedData.image}
alt="avatar"
style={{ width: '100%' }}
/>
) : (
uploadButton
)}
</Upload>
</ImgCrop>
</Form.Item>
customRequest = async ({ onSuccess, onError, file }) => {
if (!file.url && !file.preview) {
file.preview = await getBase64(file)
}
this.setState({
file: file,
selectedData: { ...this.state.selectedData, image: file.url || file.preview },
})
}
onFinish = async values => {
// when I console.log(values), the value for file : undefined
this.setState({ loading: true })
var form_data = new FormData()
for (var key in this.state.selectedData) {
form_data.set(key, this.state.selectedData[key])
}
for (var key in values) {
if (key == 'file') {
const file = values[key]
if (file != undefined) {
form_data.set(key, this.state.file)
} else {
form_data.set(key, values[key])
}
} else {
form_data.set(key, values[key])
}
}
// send the payload to server
}