UploadFile class¶
You can definepath operation function parameters to be of the typeUploadFile to receive files from the request.
You can import it directly fromfastapi:
fromfastapiimportUploadFilefastapi.UploadFile¶
UploadFile(file,*,size=None,filename=None,headers=None) Bases:UploadFile
A file uploaded in a request.
Define it as apath operation function (or dependency) parameter.
If you are using a regulardef function, you can use theupload_file.fileattribute to access the raw standard Python file (blocking, not async), useful andneeded for non-async code.
Read more about it in theFastAPI docs for Request Files.
Example¶
fromtypingimportAnnotatedfromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:Annotated[bytes,File()]):return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile):return{"filename":file.filename}Source code instarlette/datastructures.py
417418419420421422423424425426427428429430431432 | |
readasync¶
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 infastapi/datastructures.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99100101102 | |
writeasync¶
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 infastapi/datastructures.py
66676869707172737475767778798081828384 | |
seekasync¶
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 infastapi/datastructures.py
104105106107108109110111112113114115116117118119120121122 | |
closeasync¶
close()Close the file.
To be awaitable, compatible with async, this is run in threadpool.
Source code infastapi/datastructures.py
124125126127128129130 | |







