Skip to content

Using File to limit UploadFile's size should work but doesn't. #11750

Answered by chyok
Diegovsky asked this question in Questions
Discussion options

You must be logged in to vote

Hi @Diegovsky ,
you can try this:

@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 prope…

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
1 reply
@Diegovsky
Comment options

Comment options

You must be logged in to vote
3 replies
@Diegovsky
Comment options

@chyok
Comment options

@Diegovsky
Comment options

Answer selected by Diegovsky
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
3 participants