如何使用邮递员将文件发送到 fastapi 端点邮递员、发送到、如何使用、文件

2023-09-07 10:24:17 作者:陈情匿旧酒

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

I faced the difficulty of testing api using postman. Through swagger file upload functionality works correctly, I get a saved file on my hard disk. I would like to understand how to do this with the postman. I use the standard way to work with files which I use when working with Django, flask.

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

但是使用 fast API,我得到一个错误

But with fast API, I get an error

127.0.0.1:54294 - "POST /uploadfile/ HTTP/1.1" 422 Unprocessable Entity

ma​​in.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 ->二进制:image.jpeg .但得到了相同的结果

I also tried body -> binary: image.jpeg . But got the same result

推荐答案

我的代码:

from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/file/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

在 Postman 中设置

Setup in Postman

如 https://m.xsw88.com/allimgs/daicuo/20230907/5068.png (或其他)之前.相反,FastAPI 接受 file=image.png.因此错误,因为该文件是必需的,但它不存在(至少,具有该名称的键不存在).

As stated in https://m.xsw88.com/allimgs/daicuo/20230907/5069.png (or whatever). Instead, FastAPI accepts file=image.png. Thus the error, since the file is necessary, but it is not present (at least, the key with that name is not present).

附:我用 Postman v7.16.1 测试过

P.S. I tested it with Postman v7.16.1