如何使用Postman将文件发送到FastAPI端点?

问题描述 投票:0回答:2

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

Body -> form-data: key=file, value=image.jpeg

但是使用 fast API,我收到错误

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

python file-upload postman fastapi
2个回答
19
投票

我的代码:

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测试过


1
投票

正如回复中提到的,我可以看到上传的文件的密钥丢失了。在正文参数中将文件的键指定为 file

© www.soinside.com 2019 - 2024. All rights reserved.