Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

477
Visualizações
How to storage an image in MongoDB with pymongo?

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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Mongo suggest this to store files bigger than 16mb (GridFS)

I suggest you do this: First create directory in your project named "static" then do this

import uuid
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi import UploadFile, File, status
import aiofiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")


@app.post("/")
async def post_endpoint(in_file: UploadFile = File(...)):
    random_name = uuid.uuid4()
    async with aiofiles.open(f"static/{random_name}.jpg", "wb") as out_file:
        while content := await in_file.read(1024):  # async read chunk
            await out_file.write(content)


    return {"Result": "OK"}

and then save your file name in db like string.

for get image you can use this : http://127.0.0.1:8000/static/uuiduuiduuiduuiduuiduuiduuid.jpg

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda