python实现application/octet-stream上传图片文件
from urllib import parse
import urllib.request
import hashlib
def calculate_file_md5(file_path):
md5 = hashlib.md5()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
md5.update(chunk)
return md5.hexdigest()
def upload_photo(file_name="02.jpg"):
url = 'http://xxxxx.com/c_upload'
headers = {
'content-type': 'application/octet-stream',
'User-Agent': 'okhttp/3.12.10.16'
}
params ={
'share_type': 'public',
'wsc_dfp': '',
'file_md5': calculate_file_md5(file_name), # 计算文件MD5
'file_type': 'jpg',
'business_type': 'image',
}
fobj = open(file_name, "rb")
data = fobj.read()
pul = url + "?" + parse.urlencode(params)
req = urllib.request.Request(pul, data, headers) # 合成一个Request对象req
msg = urllib.request.urlopen(req) # 传递request对象给服务器
msg2 = msg.read().decode() # 读取服务器的返回结果,是否成功的标签
print(msg2)