UploadFile
类¶
你可以将*路径操作函数*的参数定义为 UploadFile
类型,以接收来自请求的文件。
你可以直接从 fastapi
导入它:
from fastapi import UploadFile
fastapi.UploadFile
¶
UploadFile(file, *, size=None, filename=None, headers=None)
Bases: UploadFile
A file uploaded in a request.
Define it as a path operation function (or dependency) parameter.
If you are using a regular def
function, you can use the upload_file.file
attribute to access the raw standard Python file (blocking, not async), useful and
needed for non-async code.
Read more about it in the FastAPI docs for Request Files.
Example¶
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}
PARAMETER | DESCRIPTION |
---|---|
file |
TYPE:
|
size |
TYPE:
|
filename |
TYPE:
|
headers |
TYPE:
|
Source code in starlette/datastructures.py
414 415 416 417 418 419 420 421 422 423 424 425 |
|
read
async
¶
read(size=-1)
Read some bytes from the file.
To be awaitable, compatible with async, this is run in threadpool.
PARAMETER | DESCRIPTION |
---|---|
size |
The number of bytes to read from the file.
TYPE:
|
Source code in fastapi/datastructures.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
write
async
¶
write(data)
Write some bytes to the file.
You normally wouldn't use this from a file you read in a request.
To be awaitable, compatible with async, this is run in threadpool.
PARAMETER | DESCRIPTION |
---|---|
data |
The bytes to write to the file.
TYPE:
|
Source code in 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)
Move to a position in the file.
Any next read or write will be done from that position.
To be awaitable, compatible with async, this is run in threadpool.
PARAMETER | DESCRIPTION |
---|---|
offset |
The position in bytes to seek to in the file.
TYPE:
|
Source code in 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()
Close the file.
To be awaitable, compatible with async, this is run in threadpool.
Source code in fastapi/datastructures.py
133 134 135 136 137 138 139 |
|