-
First Check
Commit to Help
Example Codefrom typing import Annotated
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post("/")
async def echo(file: Annotated[UploadFile, File(max_length=1000)]):
print(await file.read()) DescriptionAccording to this section in the official docs,
Operating SystemLinux Operating System DetailsNo response FastAPI Version0.111.0 Pydantic Version2.7.4 Python Version3.12.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
When you import File, you are using a function that will return a File class, that inherits from Form. And you get generic validations that only applies to certain types. For example, you can pass In your case, you are trying to use def File( # noqa: N802
default: Annotated[
Any,
Doc(
"""
Default value if the parameter field is not set.
"""
),
] = Undefined,
*,
# other params
max_length: Annotated[
Optional[int],
Doc(
"""
Maximum length for strings.
"""
), |
Beta Was this translation helpful? Give feedback.
-
Hi @Diegovsky , @app.post("/")
async def echo(file: Annotated[UploadFile, File()],
content_length: Annotated[int | None, Header(lt=1000*1024)] = None): We can use the Content-Length request header to pre-validate the file size (the unit is Bytes). For example, the code you provided implemented a check to ensure the file size is less than 1000KB. Additionally, you may notice that in the Swagger UI, the browser will automatically calculate and populate this header for you. However, please note that for other clients, you need to ensure they properly send the Content-Length header. By the way, you can directly use file.size to determine the file size (a property of the UploadFile). However, by the time the server receives the request, the file data has already been transmitted. If you want to save network bandwidth, the above approach that validate the Content-Length header before accepting the file, is more suitable for you. |
Beta Was this translation helpful? Give feedback.
Hi @Diegovsky ,
you can try this:
We can use the Content-Length request header to pre-validate the file size (the unit is Bytes). For example, the code you provided implemented a check to ensure the file size is less than 1000KB. Additionally, you may notice that in the Swagger UI, the browser will automatically calculate and populate this header for you. However, please note that for other clients, you need to ensure they properly send the Content-Length header.
By the way, you can directly use file.size to determine the file size (a prope…