Skip to content

Reading file into background task #11177

Answered by estebanx64
zekrismh asked this question in Questions
Discussion options

You must be logged in to vote

Hi @zekrismh.

The error is being raised because the UploadFile object is being closed once you pass it to the background task.

The ideal solution should be read the file within the same endpoint context and pass its content.

Here's an example

from fastapi import FastAPI, BackgroundTasks, File, UploadFile
from typing import Optional
import os

app = FastAPI()


async def get_file_content(file: UploadFile):
    return await file.read()


async def print_file_content(file_content: bytes):
    print(file_content)
    # Process the file content here


@app.post("/upload/")
async def upload_file(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
    file_content = await get_file_…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@zekrismh
Comment options

@zekrismh
Comment options

@tiangolo
Comment options

@falkben
Comment options

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