import requests def sendImg(img_path, img_name, img_type='image/jpeg'): """ :param img_path:圖片的路徑 :param img_name:圖片的名稱 :param img_type:圖片的類型,這里寫的是image/jpeg,也可以是png/jpg """ url = 'https://www.xxxxxxxxxx.com' # 自己想要請求的接口地址 with open(img_path + img_name, "rb")as f_abs:# 以2進制方式打開圖片 body = { # 有些上傳圖片時可能會有其他字段,比如圖片的時間什么的,這個根據自己的需要 'camera_code': (None, "攝像頭1"), 'image_face': (img_name, f_abs, img_type) # 圖片的名稱、圖片的絕對路徑、圖片的類型(就是后綴) "time":(None, "2019-01-01 10:00:00") } # 上傳圖片的時候,不使用data和json,用files response = requests.post(url=url, files=body).json return response if __name__=='__main__': # 上傳圖片 res = sendImg(img_path, img_name) # 調用sendImg方法 print(res)
**如果上傳圖片是數組時,value直接寫圖片路徑就可以**
文件上傳:上傳的類型是file,用到頭部信息
from urllib3 import encode_multipart_formdata import requests def sendFile(filename, file_path): """ :param filename:文件的名稱 :param file_path:文件的絕對路徑 """ url = "https://www.xxxxxxx.com" # 請求的接口地址 with open(file_path, mode="r", encoding="utf8")as f: # 打開文件 file = { "file": (filename, f.read()),# 引號的file是接口的字段,后面的是文件的名稱、文件的內容 "key": "value", # 如果接口中有其他字段也可以加上 } encode_data = encode_multipart_formdata(file) file_data = encode_data[0] # b'--c0c46a5929c2ce4c935c9cff85bf11d4\r\nContent-Disposition: form-data; name="file"; filename="1.txt"\r\nContent-Type: text/plain\r\n\r\n...........--c0c46a5929c2ce4c935c9cff85bf11d4--\r\n headers_from_data = { "Content-Type": encode_data[1], "Authorization": token } # token是登陸后給的值,如果你的接口中頭部不需要上傳字段,就不用寫,只要前面的就可以 # 'Content-Type': 'multipart/form-data; boundary=c0c46a5929c2ce4c935c9cff85bf11d4',這里上傳文件用的是form-data,不能用json response = requests.post(url=url, headers=headers_from_data, data=file_data).json() return response if __name__=='__main__': # 上傳文件 res = sendFile(filename, file_path) # 調用sendFile方法 print(res)
原文:https://blog.csdn.net/xy_best_/article/details/92839653