我正在创建一个上传表单,我可以在其中一次上传多个图像,只要我使用 Swagger UI 发布它就可以工作,但是当我使用 FastAPI docs 中提到的简单 HTML 表单尝试它时,我是收到此错误 127.0.0.1:55967 - "POST /upload-meme/ProgrammerHumor HTTP/1.1" 422 Unprocessable Entity
。
我在这里遗漏了什么?
services.py
def _is_image(filename: str):
valid_extensions = (".png", ".jpg", ".jpeg", ".gif")
return filename.endswith(valid_extensions)
def upload_image(directory_name: str, image: _fastapi.UploadFile):
if _is_image(image.filename):
timestr = time.strftime("%Y%m%d-%H%M%S")
image_name = timestr + image.filename.replace(" ", "-")
with open(f"{directory_name}/{image_name}", "wb+") as image_upload:
image_upload.write(image.file.read())
return f"{directory_name}/{image_name}"
return None
更新:我尝试使用响应模型,但现在我收到 404 Not Found
错误而不是 {"detail":[{"loc":["body","images"],"msg":"field required","type":"value_error.missing"}]}
main.py
class subreddit(BaseModel):
subreddit_name: str
@app.get('/')
def index():
content = """
<body>
<form method="post" action="/upload-meme/memes" enctype="multipart/form-data">
<input name="subreddit_name" type="file" multiple>
<input type="submit">
</form>
</body>
"""
return HTMLResponse(content=content)
@app.post('/upload-meme/', response_model=subreddit)
def post_meme(subreddit_name: subreddit = _fastapi.Form(...), images: List[_fastapi.UploadFile] = _fastapi.File(...)):
for image in images:
file_path = _service.upload_image(subreddit_name, image)
if file_path is None:
return _fastapi.HTTPException(status_code=409, detail="Invalid File Type!")
return {"filepath": _responses.FileResponse(file_path).path}
任何帮助将不胜感激。