I'm trying to upload an image using Axios inside an object. I can get a file using new FormData() and put it in an object, but submitting the image is empty. How do I upload a file in an object in combination with other JSON data?
import React, { useState } from 'react';
import axios from 'axios';
function UploadFiles() {
const [submitFile, setSubmitFile] = useState({});
const handleChange = e => {
setSubmitFile(e.target.files[0]);
};
const handleSubmit = () => {
const formData = new FormData();
formData.append('document', submitFile);
formData.append('Answer_name', 'image');
formData.append('Document', true);
formData.append('Answer', 'Got some data');
console.log(submitData) // I get formData data
const submitData = {
UUID_Formulier: '117F994F-F803-7249-91E9-EE1E7B691DFF',
answers: [formData], // this will be an empty object on calling axios.post
};
axios
.post('/submit', submitData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(() => {
console.log('success');
})
.catch(() => {
console.log('failed error');
});
};
return (
<div>
<input type="file" name="image" onChange={handleChange} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
The image must be placed in the answers array. When I put FormData in the answers array, it's an empty object. How can I put file formData into a JSON object or array then submit all?
Using Square bracket notation doesn't create an array but strings, as shown below.
