from typing import Annotated
from fastapi import FastAPI, Path, Form
from pydantic import BaseModel
import base64
class file(BaseModel):
name: str
data: str
app = FastAPI()
@app.post("/upload")
def upload(filename: str = Form(...), filedata: str = Form(...)):
image_as_bytes = str.encode(filedata) # convert string to bytes
img_recovered = base64.b64decode(image_as_bytes) # decode base64string
try:
with open("uploaded_" + filename, "wb") as f:
f.write(img_recovered)
print('fine')
except Exception:
return {"message": "There was an error uploading the file"}
return {"message": f"Successfuly uploaded {filename}"}
Backend Output:
INFO: Started server process [18183]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:45202 – “GET /docs HTTP/1.1” 200 OK
INFO: 127.0.0.1:45202 – “GET /openapi.json HTTP/1.1” 200 OK
fine
INFO: 127.0.0.1:49262 – “POST /upload HTTP/1.1” 200 OK
I tried using BaseModel and many other data types.
GreatRSingh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.