FastAPI – Uploading Files


FastAPI – Uploading Files



”;


First of all, to send a file to the server you need to use the HTML form’s enctype as multipart/form-data, and use the input type as the file to render a button, which when clicked allows you to select a file from the file system.


<html>
   <body>
      <form action="http://localhost:8000/uploader" method="POST" enctype="multipart/form-data">
         <input type="file" name="file" />
         <input type="submit"/>
      </form>
   </body>
</html>

Note that the form’s action parameter to the endpoint http://localhost:8000/uploader and the method is set to POST.

This HTML form is rendered as a template with following code −


from fastapi import FastAPI, File, UploadFile, Request
import uvicorn
import shutil
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/upload/", response_class=HTMLResponse)
async def upload(request: Request):
   return templates.TemplateResponse("uploadfile.html", {"request": request})

Visit http://localhost:8000/upload/. You should get the form with Choose File button. Click it to open the file to be uploaded.


FastAPI Uploading Files

The upload operation is handled by UploadFile function in FastAPI


from fastapi import FastAPI, File, UploadFile
import shutil
@app.post("/uploader/")
async def create_upload_file(file: UploadFile = File(...)):
   with open("destination.png", "wb") as buffer:
      shutil.copyfileobj(file.file, buffer)
   return {"filename": file.filename}

We shall use shutil library in Python to copy the received file in the server location by the name destination.png

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *