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 async
¶
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)
将一些字节写入文件。
通常情况下,您不会在请求中读取的文件上使用此方法。
为了支持异步操作,此方法在线程池中执行。
参数 | 描述 |
---|---|
数据
|
要写入文件的字节数据。
类型: |
源代码位于 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)
移动到文件中的某个位置。
任何后续的读取或写入操作都将从此位置开始。
为了支持异步操作,此方法在线程池中执行。
参数 | 描述 |
---|---|
偏移量
|
要在文件中跳转到的字节位置。
类型: |
源代码位于 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 |
|