gpt4 book ai didi

python - 如何使用 postman 将文件发送到fastapi端点

转载 作者:行者123 更新时间:2023-12-04 00:00:13 27 4
gpt4 key购买 nike

我遇到了使用 postman 测试 api 的困难。通过 swagger 文件上传功能正常工作,我在硬盘上得到了一个保存的文件。我想了解如何使用 postman 执行此操作。我使用标准方式来处理我在使用 django、flask 时使用的文件。

Body -> form-data: key=file, value=image.jpeg
但是使用fastapi,我收到一个错误
127.0.0.1:54294 - "POST /uploadfile/ HTTP/1.1" 422 Unprocessable Entity
main.py
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
img = await file.read()
if file.content_type not in ['image/jpeg', 'image/png']:
raise HTTPException(status_code=406, detail="Please upload only .jpeg files")
async with aiofiles.open(f"{file.filename}", "wb") as f:
await f.write(img)
return {"filename": file.filename}
我也试过 body -> binary: image.jpeg .但得到了相同的结果
postman query

最佳答案

我的代码:

from fastapi import FastAPI, UploadFile, File


app = FastAPI()


@app.post("/file/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
在 Postman 中设置
enter image description here
https://github.com/tiangolo/fastapi/issues/1653 中所述,文件的参数名称是您必须使用的键值。在您使用 key=file 和 value=image.png (或其他)之前。相反,FastAPI 接受 file=image.png。因此错误,因为该文件是必需的,但它不存在(至少,具有该名称的键不存在)。
我用 Postman v7.16.1 测试过
如果您仍有问题,请告诉我。

关于python - 如何使用 postman 将文件发送到fastapi端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62798421/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com