0Pricing
FastAPI Backend Development Bootcamp · บทเรียน

ข้อมูลแบบฟอร์มและการอัปโหลดไฟล์

จัดการข้อมูลจากแบบฟอร์ม HTML แบบดั้งเดิม และใช้งานการอัปโหลดไฟล์ด้วยความสามารถในตัวของ FastAPI

ข้อมูลแบบฟอร์มและการอัปโหลดไฟล์ เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Form Data Basics

When you fill out a web form (like a login or registration page) and click "submit," the data you entered is often sent as form data.

This is a traditional way for browsers to send information to a server, different from sending JSON in a request body.

Form data can be sent in two main ways:

  • application/x-www-form-urlencoded: For simple key-value pairs.
  • multipart/form-data: Used when files are involved, or for larger, more complex data.

FastAPI's Form Dependency

FastAPI makes handling form data easy using the Form dependency from fastapi.

It works similarly to Query or Path parameters, but it tells FastAPI to expect the data in the request body as form fields.

You import it like this: from fastapi import FastAPI, Form.

Basic Form Endpoint Example

Let's create an endpoint that accepts a username and password as form data. Notice how username and password are explicitly marked with Form(...).

This tells FastAPI to parse them from the form body, not as JSON or query parameters.

from fastapi import FastAPI, Form
import uvicorn

app = FastAPI()

@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username, "message": "Login successful!"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Interacting with Form Data

You can test this endpoint using tools like curl or by creating a simple HTML form. The -d flag in curl sends form data.

Make sure your FastAPI application from the previous scene is running!

curl -X POST "http://127.0.0.1:8000/login/" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "username=coddy&password=secret"

File Uploads Explained

Uploading files (like images, documents, or videos) is a common web task. This type of data is sent using multipart/form-data encoding.

FastAPI provides special tools to handle these uploads efficiently, allowing you to access file contents and metadata.

FastAPI's UploadFile

For file uploads, FastAPI uses the UploadFile class (from fastapi) along with the File dependency.

When you declare a parameter with File(...) and type-hint it as UploadFile, FastAPI handles the file stream.

  • filename: The name of the uploaded file.
  • content_type: The file's MIME type (e.g., image/jpeg).
  • file: A SpooledTemporaryFile object, allowing you to read its contents.
from fastapi import FastAPI, File, UploadFile
import uvicorn

app = FastAPI()

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename, "content_type": file.content_type}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Saving One Uploaded File

After receiving an UploadFile, you can read its content and save it to a local disk or cloud storage. Here's how to save it locally.

Remember to handle potential errors during file operations.

from fastapi import FastAPI, File, UploadFile
import uvicorn
import shutil
import os

app = FastAPI()

# Ensure the 'files' directory exists
os.makedirs("files", exist_ok=True)

@app.post("/uploadandsave/")
async def upload_and_save_file(file: UploadFile = File(...)):
    file_location = f"files/{file.filename}"
    with open(file_location, "wb+") as file_object:
        shutil.copyfileobj(file.file, file_object)
    return {"message": f"File '{file.filename}' saved at '{file_location}'"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Uploading Many Files

What if you need to upload several files at once? FastAPI supports this by allowing you to define a parameter as a list of UploadFile.

Each file in the list will be an UploadFile object, which you can then process individually.

from fastapi import FastAPI, File, UploadFile
from typing import List
import uvicorn

app = FastAPI()

@app.post("/uploadmultiple/")
async def create_upload_files(files: List[UploadFile] = File(...)):
    uploaded_filenames = [file.filename for file in files]
    return {"filenames": uploaded_filenames, "message": "Files received!"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Saving Multiple Uploads

Similar to single files, you can iterate through the list of UploadFile objects and save each one. This is useful for photo galleries or document uploads.

Always ensure proper error handling and secure file storage practices in a real application.

from fastapi import FastAPI, File, UploadFile
from typing import List
import uvicorn
import shutil
import os

app = FastAPI()

# Ensure the 'files' directory exists
os.makedirs("files", exist_ok=True)

@app.post("/uploadandsavemultiple/")
async def upload_and_save_multiple_files(files: List[UploadFile] = File(...)):
    saved_files = []
    for file in files:
        file_location = f"files/{file.filename}"
        with open(file_location, "wb+") as file_object:
            shutil.copyfileobj(file.file, file_object)
        saved_files.append(file.filename)
    return {"message": f"Successfully uploaded: {', '.join(saved_files)}"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Form & File Check

You've learned about handling form data and file uploads. Let's test your understanding!

Lesson Summary

Great job! In this lesson, you mastered how to handle traditional form data and robust file uploads in FastAPI.

  • We used Form(...) for simple key-value form fields.
  • We explored UploadFile and File(...) for single and multiple file uploads.
  • You learned to save uploaded files to your server.

These techniques are crucial for building interactive web applications. Keep practicing!

คำถามที่พบบ่อย

บทเรียน “ข้อมูลแบบฟอร์มและการอัปโหลดไฟล์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ข้อมูลแบบฟอร์มและการอัปโหลดไฟล์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ข้อมูลแบบฟอร์มและการอัปโหลดไฟล์”

จัดการข้อมูลจากแบบฟอร์ม HTML แบบดั้งเดิม และใช้งานการอัปโหลดไฟล์ด้วยความสามารถในตัวของ FastAPI คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “ข้อมูลแบบฟอร์มและการอัปโหลดไฟล์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. โมเดล Pydantic สำหรับเนื้อหาคำขอ
  2. โมเดลการตอบกลับและรหัสสถานะ
  3. ข้อมูลแบบฟอร์มและการอัปโหลดไฟล์
  4. ส่วนหัว คุกกี้ และการตอบกลับแบบกำหนดเอง
← กลับไปที่ FastAPI Backend Development Bootcamp