Frontend = React, backend = FastApi. How can I simply send an image from the frontend, and have the backend saving it to the local disk ? I've tried different ways: in an object, in a base64 string, etc. But I can't manage to deserialize the image in FastApi. It looks like an encoded string, I tried writing it to a file, or decoding it, but with no success.
const [selectedFile, setSelectedFile] = useState(null);
const changeHandler = (event) => {setSelectedFile(event.target.files[0]); };
const handleSubmit = event => {
const formData2 = new FormData();
formData2.append(
"file",
selectedFile,
selectedFile.name
);
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData2 // Also tried selectedFile
};
fetch('http://0.0.0.0:8000/task/upload_image/'+user_id, requestOptions)
.then(response => response.json())
}
return ( <div
<form onSubmit={handleSubmit}>
<fieldset>
<label htmlFor="image">upload picture</label><br/>
<input name="image" type="file" onChange={changeHandler} accept=".jpeg, .png, .jpg"/>
</fieldset>
<br/>
<Button color="primary" type="submit">Save</Button>
</form>
</div>
);
And the backend:
@router.post("/upload_image/{user_id}")
async def upload_image(user_id: int, request: Request):
body = await request.body()
# fails (TypeError)
with open('/home/backend/test.png', 'wb') as fout:
fout.writelines(body)
I also tried to simply mimic the client with something like this:
curl -F media=@/home/original.png http://0.0.0.0:8000/task/upload_image/3
but same result...
----- [Solved] Removing user_id for simplicity. The server part must look like this:
@router.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
out_path = 'example/path/file'
async with aiofiles.open(out_path, 'wb') as out_file:
content = await file.read()
await out_file.write(content)
And for some reason, the client part should not include the content-type in the headers:
function TestIt ( ) {
const [selectedFile, setSelectedFile] = useState(null);
const [isFilePicked, setIsFilePicked] = useState(false);
const changeHandler = (event) => {
setSelectedFile(event.target.files[0]);
setIsFilePicked(true);
};
const handleSubmit = event => {
event.preventDefault();
const formData2 = new FormData();
formData2.append(
"file",
selectedFile,
selectedFile.name
);
const requestOptions = {
method: 'POST',
//headers: { 'Content-Type': 'multipart/form-data' }, // DO NOT INCLUDE HEADERS
body: formData2
};
fetch('http://0.0.0.0:8000/task/uploadfile/', requestOptions)
.then(response => response.json())
.then(function (response) {
console.log('response')
console.log(response)
});
}
return ( <div>
<form onSubmit={handleSubmit}>
<fieldset>
<input name="image" type="file" onChange={changeHandler} accept=".jpeg, .png, .jpg"/>
</fieldset>
<Button type="submit">Save</Button>
</form>
</div>
);
}