I'm doing a simple CRUD with FastAPI to store an image and its information in MongoDB, so far this is my code:
@app.post("/postImage")
async def image_post(id: str, author: str, title: str, file: UploadFile = File(...)):
file.filename = f"{uuid.uuid4()}.jpg"
contents = await file.read()
image = base64.b64decode(contents)
data = {"_id": id, "author": author, "title": title ,"data": image, "posted": False,"uploaded": datetime.now()}
try:
collection.insert_one(data)
except:
print('Error')
return("Added successfully")
However, when I'm trying to convert the bytes to string it returns me an error.
image = base64.b64decode(contents)
print(image.decode('utf-8'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 11: invalid start byte
I've tried many alternatives, but I don't know what's wrong.
image = base64.b64encode(contents)before inserting the document? Or maybe just store it as BSON binary data?