Skip to content

UplaodFile is already closed when received by post function #146

Open
@guyernest

Description

@guyernest

I'm trying to upload a file from a form with FastUI and I'm consistently getting I/O operation on closed file. error.

The code is an adaptation of the demo:

class UploadForm(BaseModel):
    text_file: Annotated[UploadFile, FormFile(accept='text/plain')] = Field(
        description='Upload a text file'
    )

@router.get('/content/{kind}', response_model=FastUI, response_model_exclude_none=True)
def form_content(kind: FormKind):
    match kind:
        ...
        case 'text_file':
            return [
                c.Heading(text='Text File', level=2),
                c.Paragraph(text='Upload the text file.'),
                c.ModelForm(model=UploadForm, submit_url='/api/text_file_upload'),
            ]
        case _:
            raise ValueError(f'Invalid kind {kind!r}')

@router.post('/text_file_upload', response_model=FastUI, response_model_exclude_none=True)
async def text_file_form_post(form: Annotated[UploadForm, fastui_form(UploadForm)]):
    # print(form)
    file: UploadFile = form.text_file
    print(file.filename)
    print(file.file.closed)
    contents = await file.file.read()

The print message at the end prints the name of the file that I choose correctly and then True for the file to be closed.
Everything I try to read the contents of the file gives I/O operation on closed file. error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions