What is the difference between using File() and UploadFile for file uploads in FastAPI?
File() reads the uploaded file into memory as a bytes object, so it is intended for relatively small files. UploadFile creates a Python SpooledTemporaryFile object that is kept mostly on the server's disk, making it better for large files and supporting methods like read(), write(), and seek().
In FastAPI, File() and UploadFile are two different ways to accept file uploads. With File(), the upload is encoded as a form element and FastAPI pulls it up in chunks and reassembles it in memory as a bytes object. This means File() should only be used for relatively small files. In a path function, File() appears as a default with parentheses, such as small_file: bytes = File(). For large files, UploadFile is preferred. UploadFile creates a Python SpooledTemporaryFile object that resides mostly on the server's disk instead of memory, and it provides file-like methods such as read(), write(), and seek(), plus attributes like size and filename. Both file upload techniques benefit from an asynchronous path function to avoid blocking the web server during upload.
Key points
- File() stores file content in memory as bytes, so it is only for small files.
- UploadFile creates a SpooledTemporaryFile stored mostly on disk, making it suitable for large files.
- UploadFile supports file-like methods including read(), write(), and seek().
- File() appears with parentheses in the function signature, while UploadFile is used as a class annotation.
- Using async def for the path function is recommended to avoid blocking the server during uploads.
FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition · O'Reilly Media, Inc.