๐ฏ Poin-Poin Utama Modul Ini:
- Menginstal package
python-multipartuntuk menangani form-data UploadFilemenggunakan penanganan berbasis file spooled di memori/disk yang sangat efisien- Metode async
.read(),.write(),.seek()
๐ Upload File & Form Processing
Untuk mengunggah gambar profil postingan atau dokumen PDF, FastAPI menyediakan kelas khusus UploadFile yang tidak menghabiskan RAM server.
๐ป Kode Form Data & File Saving
main.py
import shutil
from fastapi import FastAPI, File, UploadFile, Form
app = FastAPI()
@app.post("/upload-avatar/")
async def upload_avatar(
username: str = Form(...),
file: UploadFile = File(...)
):
file_path = f"static/avatars/{file.filename}"
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {"username": username, "avatar_url": file_path}