import requests import json def upload_image_with_json( url: str, image_path: str, image_type: str = "front_face", image_name: str = "未命名", json_path: str = '' ): """ 向指定接口上传图片及附带的 JSON 数据。 参数: url (str): 接口 URL,例如 http://127.0.0.1:7745/api/images/insert/6 image_path (str): 图片文件路径 image_type (str): 图片类型,例如 'front_face' image_name (str): 图片名称 json_data (str | dict | None): JSON 内容,可以是字符串、字典或 None 返回: requests.Response: 服务器响应对象 """ with open(json_path, "r", encoding="utf-8") as f: json_data_str = f.read() files = { "image": (image_path, open(image_path, "rb"), "image/gif") } data = { "image_type": image_type, "image_name": image_name, "json_data_str": json_data_str } headers = { "accept": "application/json" } # 发送 POST 请求 response = requests.post(url, headers=headers, files=files, data=data) return response def send4img(): send_url = "http://127.0.0.1:7745/api/images/insert/7" front_face_img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面面\rectify_center_img.jpg" front_face_json_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面面\front_face_score.json" front_edge_img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面边角\rectify_center_img.jpg" front_edge_json_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面边角\front_corner_edge_score.json" back_face_img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\背面面\rectify_center_img.jpg" back_face_json_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\背面面\back_face_score.json" back_edge_img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\背面边角\rectify_center_img.jpg" back_edge_json_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\背面边角\back_corner_edge_score.json" data = {"front_face": {"image": front_face_img_path, "json_data": front_face_json_path}, "front_edge": {"image": front_edge_img_path, "json_data": front_edge_json_path}, "back_face": {"image": back_face_img_path, "json_data": back_face_json_path}, "back_edge": {"image": back_edge_img_path, "json_data": back_edge_json_path}} for k, v in data.items(): resp = upload_image_with_json( url=send_url, image_path=v['image'], image_type=k, image_name="", json_path=v['json_data'] ) print(f"{k} Status:", resp.status_code) print("Response:", resp.text) if __name__ == "__main__": send4img() # resp = upload_image_with_json( # url="http://127.0.0.1:7745/api/images/insert/6", # image_path="v2-28c2dced87172b004d40eedc38e7889a_b.gif", # image_type="front_face", # image_name="星海", # json_data={"2343": "阿萨"} # ) # # print("Status:", resp.status_code) # print("Response:", resp.text)