Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

FastAPI File Upload

FastAPI File Upload

FastAPI provides File and UploadFile two ways to handle file uploads, supporting single-file uploads and mixed form-and-file uploads.


Install dependencies

File uploads also depend on python-multipart:

pip install python-multipart


Using UploadFile

UploadFile is the recommended approach, as it provides a richer interface for accessing file information:

Example

from

fastapi

import

FastAPI

,

UploadFile

app

=

FastAPI

(

)

@

app.

post

(

"/uploadfile/"

)

async

def

create_upload_file

(

file

: UploadFile

)

:

   

Attributes and Methods Provided by UploadFile

   

return

{

       

"filename"

:

file

.

filename

,

         

File Name

       

"content_type"

:

file

.

content_type

,

 

File MIME type

       

"size"

:

file

.

size

,

                 

File size (bytes)

   

}

UploadFile attributes and methods:

Attribute / method Type Description
filename str \| None Original filename of the uploaded file
content_type str \| None MIME type of the file (such as image/png)
file SpooledTemporaryFile File-like object that can read the file content
size int \| None File size (bytes)
read() Method Read the file content as bytes
write() Method Write content to the file
seek() Method Move the file pointer position
close() Method Closing a File

UploadFile Uses "SpooledTemporaryFile" to store file content; small files are kept in memory and large files are automatically written to disk, making it more memory-efficient than bytes in terms of memory usage.


Using File to Receive File Content

File Read the file content directly as bytes, suitable for small files:

Example

from

fastapi

import

FastAPI

,

File

app

=

FastAPI

(

)

@

app.

post

(

"/files/"

)

async

def

create_file

(

file

:

bytes

=

File

(

)

)

:

   

file is the raw byte data of the file

   

return

{

"file_size"

:

len

(

file

)

}

File The difference between UploadFile comparison:

Comparison Item File UploadFile
Data Type bytes File object
Memory Usage Entire file loaded into memory Large files automatically written to disk
File information None (content only) Has filename, type, and size
Applicable scenarios Small files Large files and scenarios requiring file information

Optional File Upload

Using a default value None makes file upload optional:

Example

from

fastapi

import

FastAPI

,

UploadFile

app

=

FastAPI

(

)

@

app.

post

(

"/uploadfile/"

)

async

def

create_upload_file

(

file

: UploadFile |

None

=

None

)

:

   

if

not

file

:

       

return

{

"message"

:

"No file uploaded"

}

   

return

{

"filename"

:

file

.

filename

}


Multiple File Uploads

Use a list to receive multiple files:

Example

from

fastapi

import

FastAPI

,

UploadFile

app

=

FastAPI

(

)

@

app.

post

(

"/uploadfiles/"

)

async

def

create_upload_files

(

files:

list

[

UploadFile

]

)

:

   

return

{

"filenames"

:

[

file

.

filename

for

file

in

files

]

}


Mixed Form and File Upload

You can receive form data and files in the same route:

Example

from

fastapi

import

FastAPI

,

File

,

UploadFile

,

Form

app

=

FastAPI

(

)

@

app.

post

(

"/items/"

)

async

def

create_item

(

   

Form fields

    name:

str

=

Form

(

...

)

,

    description:

str

|

None

=

Form

(

None

)

,

   

File upload

   

file

: UploadFile |

None

=

None

,

)

:

    result

=

{

"name"

: name

,

"description"

: description

}

   

if

file

:

        result

[

"filename"

]

=

file

.

filename

   

return

result


Save the Uploaded File

The following example shows how to save an uploaded file to disk:

Example

import

shutil

from

fastapi

import

FastAPI

,

UploadFile

app

=

FastAPI

(

)

@

app.

post

(

"/uploadfile/"

)

async

def

create_upload_file

(

file

: UploadFile

)

:

   

Save the uploaded file to the specified path

   

with

open

(

f

"uploads/{file.filename}"

,

"wb"

)

as

buffer:

       

shutil

.

copyfileobj

(

file

.

file

,

buffer

)

   

return

{

"filename"

:

file

.

filename

,

"message"

:

"File uploaded successfully"

}

In real projects, when uploading files you should: 1) validate the file type and size; 2) use a safe filename (to avoid path traversal attacks); 3) restrict the permissions of the upload directory; 4) use streaming instead of reading all at once for large files.


Summary