FastAPI 通过 Postman 上传文件时引发 422 Unprocessable Entity 错误

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

我正在使用方法

POST
通过Postman上传一个文件并将其保存到我的本地目录。但是出现了422(Unprocessable实体),如下图:

enter image description here

我选择了二进制文件并将其上传到 Postman,正如您在发布的图片中看到的那样。

下面是我的 FastAPI 后端的样子:

main.py

from fastapi import FastAPI
from api.endpoints.vendor import router

app = FastAPI(title='Vendor Acknolegment API')
app.include_router(router, prefix='/vendor', tags=['vendor confirmation'])

if __name__ == '__main__':
    import uvicorn
    print("entered here")
    uvicorn.run("main:app", host="0.0.0.0", port=8000,
                log_level='info', reload=True)

供应商.py

from fastapi import APIRouter, status, File, UploadFile
#from lxml import etree
import os

# file path
UPLOAD_DIR = r"c:\ack"

# check if the directory exists.
os.makedirs(UPLOAD_DIR, exist_ok=True)

# creates the endpoint path
router = APIRouter()

# POST Ack
@router.post("/ack/", status_code=status.HTTP_201_CREATED)
async def upload_ack(file: UploadFile = File(...)):
    # define the complete path where the file will be saved.
    file_location = os.path.join(UPLOAD_DIR, file.filename)

    with open(file_location, "wb") as f:
        f.write(await file.read())

    return {"message": f"The file '{file.filename}' has been successfully saved into the server."}
python file-upload postman fastapi http-status-code-422
1个回答
0
投票

这个答案中所述,并在这个答案中演示,使用

UploadFile
时,文件将上传为
multipart/form-data
。因此,在 Postman 中,您应该转到
Body
->
form-data
并输入为 API 端点中的 UploadFile 参数指定的
key
名称 - 在您的 cace 中,即
file
,因为您定义了它为
file: UploadFile = File(...)
— 并将文件上传到
value
部分。

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