UploadFile
類別¶
您可以定義路徑操作函式的參數類型為 UploadFile
來接收請求中的檔案。
您可以直接從 fastapi
導入它。
from fastapi import UploadFile
fastapi.UploadFile ¶
UploadFile(file, *, size=None, filename=None, headers=None)
基底:UploadFile
請求中上傳的檔案。
將其定義為路徑操作函式(或依賴項)的參數。
如果您使用的是普通的 def
函式,您可以使用 upload_file.file
屬性來訪問原始的標準 Python 檔案(阻塞式,非異步),這對於非異步程式碼很有用且是必要的。
在FastAPI 的請求檔案文件中了解更多資訊。
範例¶
from typing import Annotated
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(file: Annotated[bytes, File()]):
return {"file_size": len(file)}
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):
return {"filename": file.filename}
參數 | 說明 |
---|---|
file (檔案)
|
類型: |
size (大小)
|
類型: |
filename (檔案名稱)
|
類型: |
headers (標頭)
|
類型: |
原始碼位於 starlette/datastructures.py
414 415 416 417 418 419 420 421 422 423 424 425 |
|
read 非同步
¶
read(size=-1)
從檔案中讀取一些位元組。
為了使其可等待,並與非同步相容,此操作在執行緒池中運行。
參數 | 說明 |
---|---|
size (大小)
|
要從檔案中讀取的位元組數。
類型: |
原始碼位於 fastapi/datastructures.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
write async
¶
write(data)
寫入一些位元組到檔案。
通常您不會對從請求中讀取的檔案使用此方法。
為了使其可等待,並與非同步相容,此操作在執行緒池中運行。
參數 | 說明 |
---|---|
data
|
要寫入檔案的位元組。
類型: |
原始碼位於 fastapi/datastructures.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
|
seek async
¶
seek(offset)
移動到檔案中的某個位置。
任何後續的讀取或寫入都將從該位置開始。
為了使其可等待,並與非同步相容,此操作在執行緒池中運行。
參數 | 說明 |
---|---|
offset
|
要在檔案中搜尋的位元組位置。
類型: |
原始碼位於 fastapi/datastructures.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
|
close async
¶
close()
關閉檔案。
為了使其可等待,並與非同步相容,此操作在執行緒池中運行。
原始碼位於 fastapi/datastructures.py
133 134 135 136 137 138 139 |
|