The 422
错误响应正文将包含有关缺少哪个字段或与预期格式不匹配的字段的错误消息。由于您尚未提供(请这样做),我的猜测是由于您定义的方式而触发了该错误images
端点中的参数。自从images
预计将是一个List
of File
(s),您应该使用File
键入而不是Form
。例如:
images: List[UploadFile] = File(...)
^^^^
使用时UploadFile
, 你不必使用File()在参数的默认值中,这意味着以下内容也应该有效:
images: List[UploadFile]
因此,FastAPI 端点应类似于以下内容:
@app.post("/user/register")
async def register_user(name: str = Form(...), images: List[UploadFile] = File(...)):
pass
在前端,请确保使用body
(not data
) 中的参数fetch()函数来传递FormData对象(参见MDN Web 文档中的示例)。例如:
var nameInput = document.getElementById('nameInput');
var imagesInput = document.getElementById('imagesInput');
var formData = new FormData();
formData.append('name', nameInput.value);
for (const file of imagesInput.files)
formData.append('images', file);
fetch('/user/register', {
method: 'POST',
body: formData,
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
请看一下这个答案, 也这个答案,其中提供了有关如何上传多个的工作示例files
and form
使用前端的 Fetch API 将数据传输到 FastAPI 后端。
至于手动指定Content-Type
发送时multipart/form-data
, you don't必须(并且不应该)这样做,而是让浏览器设置Content-Type
——请看一下这个答案更多细节。