Home >Backend Development >Python Tutorial >How to Efficiently Upload Files to a FastAPI Server Using `form-data`?

How to Efficiently Upload Files to a FastAPI Server Using `form-data`?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 20:30:13474browse

How to Efficiently Upload Files to a FastAPI Server Using `form-data`?

Uploading Files with FastAPI Using form-data and SpooledTemporaryFile

To upload files using FastAPI with multipart/form-data, it's recommended to install python-multipart as multipart files are sent via form-data.

pip install python-multipart

Here's an improved example of uploading a file using FastAPI:

from fastapi import File, UploadFile
from typing import List

@app.post("/upload")
def upload(file: UploadFile = File(...)):
    try:
        # Using file.file for synchronous operations (e.g., opening a file on disk)
        contents = file.file.read()
        with open(file.filename, 'wb') as f:
            f.write(contents)
    except Exception:
        return {"message": "An error occurred while uploading the file."}
    finally:
        file.file.close()

    return {"message": f"Successfully uploaded {file.filename}"}

If you need to process larger files in chunks, consider reading the file in smaller increments. You can either use a manual loop:

@app.post("/upload")
def upload(file: UploadFile = File(...)):
    try:
        with open(file.filename, 'wb') as f:
            while contents := file.file.read(1024 * 1024):
                f.write(contents)
    except Exception:
        return {"message": "An error occurred while uploading the file."}
    finally:
        file.file.close()

    return {"message": f"Successfully uploaded {file.filename}"}

Or, use the shutil.copyfileobj() method, which reads and writes data in chunks:

from shutil import copyfileobj

@app.post("/upload")
def upload(file: UploadFile = File(...)):
    try:
        with open(file.filename, 'wb') as f:
            copyfileobj(file.file, f)
    except Exception:
        return {"message": "An error occurred while uploading the file."}
    finally:
        file.file.close()

    return {"message": f"Successfully uploaded {file.filename}"}

Additional Notes:

  • FastAPI uses SpooledTemporaryFile for file upload, which stores data in memory. For files larger than 1MB, data is written to a temporary file on disk.
  • If defining an endpoint with async def, use asynchronous file processing as mentioned in this answer: [https://stackoverflow.com/a/69868184/6616846](https://stackoverflow.com/a/69868184/6616846)
  • For uploading multiple files, you can use a list of UploadFile objects in your endpoint function.
  • For HTML form examples, refer to the links provided in the original answer.

The above is the detailed content of How to Efficiently Upload Files to a FastAPI Server Using `form-data`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn