I am trying to send a file from my React client to my Flask server.
State that holds file
const [fileToUpload, setFileToUpload] = useState(null)
form
<React.Fragment>
<p className='margin-top' style={pStyles}>Attach your file</p>
<form onSubmit={handleFileUpload} encType='multipart/form-data'>
<input
multi='false'
type='file'
onChange={(e) => handleSetFileValues(e)}
/>
{currentCheck === 'file-radio' ? (
<button type='submit' className='btn-blue'>Upload</button>
) : (
null
)}
</form>
</React.Fragment>
handleSetFileValues
const handleSetFileValues = (e) => {
setFileToUpload(e.target.files[0])
setFileUrlToUpload('')
}
handleFileUpload
const handleFileUpload = async (e) => {
// if (fileTitle === '' || fileToUpload !== null) return;
e.preventDefault()
const formData = new FormData();
formData.append("file", fileToUpload);
const { data, success, errorMessage } = await addServiceFile(service.id, formData, fileTitle)
if (success) {
console.log('res', data)
} else {
console.log('ERROR', errorMessage)
}
}
Upon submision I recieve a 400 res from the server. Logging formData
shows an empty object, and the file
object in the req payload is an empty object as well. any advice here would be great.
addServiceFile
export async function addServiceFile(serviceId, fileToUpload, fileLabel) {
try {
const body = {
file: fileToUpload,
file_label: fileLabel
};
return await awsApiRequest({
method: 'POST',
path: `/service/${serviceId}/file-data`,
params: {
body: body,
},
});
} catch (error) {
return error;
}