FastAPI Tutorial
Selected Reading
- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
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 cpcked 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. Cpck it to open the file to be uploaded.
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 pbrary in Python to copy the received file in the server location by the name destination.png
Advertisements