使用python 的request庫寫接口測試代碼時,經(jīng)常會遇到上傳文件的場景。本文就是上傳例子。
比如,后端提供了文件上傳接口,使用python調(diào)用接口上傳圖片等附件,直接上代碼
from urllib3 import encode_multipart_formdata
import requests
host = "http://*.*.*.*:80/"
def upload():
url = "upload/public"
params = {
}
header = {
"content-type":"application/json"
}
data = {
}
try:
filename="pic.jpeg"
file_path = "/Users/admin/Downloads/pic.jpeg"
data['file']= (filename, open(file_path,'rb').read())
encode_data = encode_multipart_formdata(data)
data = encode_data[0]
header['Content-Type'] = encode_data[1]
r = requests.post(url=host + url, headers=header, data=data)
print(r)
print("返回值:" + r.text)
except Exception as e:
print(e)
if __name__ == "__main__":
upload()