嘗試使用 FastAPI 通過動態 HTML 表單上傳多個檔案。
服務器端,表單通過(如 type starlette.datastructures.FormData),但檔案沒有通過。我能看到的只是字串形式的檔案名。
根據檔案,如果我嘗試:
@app.post("/modules/function")
async def function(request: Request):
form = await request.form()
filename = form["upload_file"].filename
contents = await form["upload_file"].read()
它'str' object has no attribute 'read'在第 4 行失敗。
從檔案中,form["upload_file"]應該是 typestarlette.datastructures.UploadFile但我把它作為 type str。
看似顯而易見的解決方案是在路徑中宣告檔案,但由于表單是動態的,我無法確定每次將傳入多少檔案,因此我需要能夠從FormData.
任何指標?
uj5u.com熱心網友回復:
找到了。簡單的錯誤。包含enctype="multipart/form-data"在 html 表單標簽中。當您包含檔案上傳時,它不會自動默認為此。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/373577.html
上一篇:xxx.value和xxx.options[xxx.selectedIndex].value有什么區別,用JavaScript獲取所選選項的值?
