Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

475
Views
¿Cómo almacenar una imagen en MongoDB con pymongo?

Estoy haciendo un CRUD simple con FastAPI para almacenar una imagen y su información en MongoDB, hasta ahora este es mi código:

 @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")

Sin embargo, cuando intento convertir los bytes en cadenas, me devuelve un 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

He probado muchas alternativas, pero no sé cuál es el problema.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Mongo sugiere esto para almacenar archivos de más de 16 mb (GridFS)

Le sugiero que haga esto: primero cree un directorio en su proyecto llamado "estático" y luego haga esto

 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"}

y luego guarde su nombre de archivo en db como una cadena.

para obtener la imagen, puede usar esto: http://127.0.0.1:8000/static/uuiduuiduuiduuiduuiduuiduuid.jpg

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!