import aiohttp
import asyncio
from config import Config

async def upload(url, channel, classIndex, nvr, videoTime, filename, imgContent, rateLicensePlate, rateSpeed):
    payload = {
        'channel': channel,
        'classIndex': classIndex,
        'ip': nvr,
        'videoTime': videoTime,
        'rateLicensePlate' : rateLicensePlate,
        'rateSpeed' : rateSpeed
    }

    # 使用 aiohttp.FormData 构建文件上传的请求体
    data = aiohttp.FormData()
    for key, value in payload.items():
        data.add_field(key, value)
    
    # 文件上传，注意这里是 'file' 字段
    data.add_field('file', imgContent, filename=filename, content_type='image/jpeg')

    # 发送异步 POST 请求
    async with aiohttp.ClientSession() as session:
        async with session.post(url, data=data) as response:
            text = await response.text()
            return text

if __name__ == "__main__":
    # for test
    conf = Config.get("test")
    url = conf["url"]
    channel = conf["channel"]
    classIndex = conf["classIndex"]
    nvr = conf["nvr"]

    # 测试配置
    # channel = "64"
    # classIndex = "68"
    # nvr = "172.19.152.231"
    # 生产配置
    channel = "251"
    classIndex = "101"
    nvr = "172.16.20.251"
    filename = "0-detectionPicture.jpg"
    with open(filename, "rb") as f:
        imgContent = f.read()
    videoTime = "2024-12-05 11:43:33"
    async def main():
        response = await upload(url, channel, classIndex, nvr, videoTime, filename, imgContent)
        print(await response.text())  # 获取响应文本内容
    asyncio.run(main())