【问题标题】:Starlette FormData only provides names of files but not actual filesStarlette FormData 仅提供文件名,但不提供实际文件
【发布时间】:2022-01-06 23:31:45
【问题描述】:

尝试使用 FastAPI 通过动态 HTML 表单上传多个文件。

在服务器端,表单可以通过(键入starlette.datastructures.FormData),但文件没有通过。我能看到的只是文件名作为字符串。

根据docs,如果我尝试:

@app.post("/modules/function")
async def function(request: Request):
    form = await request.form()
    filename = form["upload_file"].filename
    contents = await form["upload_file"].read()

第 4 行出现 'str' object has no attribute 'read' 失败。

从文档中,form["upload_file"] 应该是 starlette.datastructures.UploadFile 类型,但我得到的是 str 类型。

看似显而易见的解决方案是在路径中声明文件,但由于表单是动态的,我无法判断每次将有多少文件,所以我需要能够从 FormData 检索它们。

任何指针?

【问题讨论】:

    标签: python forms file-upload fastapi starlette


    【解决方案1】:

    找到了。简单的错误。在 html 表单标签中包含 enctype="multipart/form-data"。当您包含文件上传时,它不会自动默认为这个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2017-03-15
      • 1970-01-01
      • 2017-10-28
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多