掃二維碼與項(xiàng)目經(jīng)理溝通
我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問(wèn)/技術(shù)咨詢(xún)/運(yùn)營(yíng)咨詢(xún)/技術(shù)建議/互聯(lián)網(wǎng)交流
FastAPI 支持同時(shí)使用 File 和 Form 定義文件和表單字段。

“只有客戶(hù)發(fā)展了,才有我們的生存與發(fā)展!”這是創(chuàng)新互聯(lián)公司的服務(wù)宗旨!把網(wǎng)站當(dāng)作互聯(lián)網(wǎng)產(chǎn)品,產(chǎn)品思維更注重全局思維、需求分析和迭代思維,在網(wǎng)站建設(shè)中就是為了建設(shè)一個(gè)不僅審美在線(xiàn),而且實(shí)用性極高的網(wǎng)站。創(chuàng)新互聯(lián)對(duì)網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、網(wǎng)站制作、網(wǎng)站開(kāi)發(fā)、網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站優(yōu)化、網(wǎng)絡(luò)推廣、探索永無(wú)止境。
說(shuō)明
接收上傳文件或表單數(shù)據(jù),要預(yù)先安裝 python-multipart。
例如,pip install python-multipart。
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(...), fileb: UploadFile = File(...), token: str = Form(...)
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
創(chuàng)建文件和表單參數(shù)的方式與 Body 和 Query 一樣:
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(...), fileb: UploadFile = File(...), token: str = Form(...)
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
文件和表單字段作為表單數(shù)據(jù)上傳與接收。
聲明文件可以使用 bytes 或 UploadFile 。
警告
可在一個(gè)路徑操作中聲明多個(gè) File 與 Form 參數(shù),但不能同時(shí)聲明要接收 JSON 的 Body 字段。因?yàn)榇藭r(shí)請(qǐng)求體的編碼為 multipart/form-data,不是 application/json。
這不是 FastAPI 的問(wèn)題,而是 HTTP 協(xié)議的規(guī)定。
在同一個(gè)請(qǐng)求中接收數(shù)據(jù)和文件時(shí),應(yīng)同時(shí)使用 File 和 Form。

我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問(wèn)/技術(shù)咨詢(xún)/運(yùn)營(yíng)咨詢(xún)/技術(shù)建議/互聯(lián)網(wǎng)交流