-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedia_up.py
62 lines (51 loc) · 1.98 KB
/
media_up.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python
# -*-coding:utf-8-*-
# filename: media_up.py
'''
@author: YHui
@contact: [email protected]
@software: pycharm
@file: media_up.py
@time: 2017/8/30 14:23
'''
from basic import Basic
# import urllib2
import requests
import os
import poster.encode
from poster.streaminghttp import register_openers
class Media(object):
def __init__(self):
register_openers()
# 上传图片
def uplaod(self, accessToken, filePath, mediaType,name):
# 接下来的部分,是请求的官方部件,不过不能用,用requests库很多问题,还是继续用官方的版本比较稳妥
# param = {'media': openFile}
# postData, postHeaders = poster.encode.multipart_encode(param)
# postUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s" % (accessToken, mediaType)
# request = urllib2.Request(postUrl, postData, postHeaders)
# urlResp = urllib2.urlopen(request)
# 结束上传请求
# 此处代码可用,关键在于提交足够的表头
openFile = open(filePath, "rb")
postUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s" % (accessToken, mediaType)
files = {'media': ('%s' % (name), openFile, 'image/png')}
urlResp = requests.post(postUrl, files=files)
openFile.close()
urlResp.json()
media_id = urlResp["media_id"]
fmediaId = open("media.txt", 'a')
fmediaId.write(filePath[22:])
fmediaId.write('\t')
fmediaId.write(media_id)
fmediaId.write('\n')
fmediaId.close()
print urlResp
if __name__ == '__main__':
myMedia = Media()
accessToken = Basic().get_access_token()
picname = os.listdir('D:\\material\picture\cover')
for i in picname:
filePath = "D:\\material\picture\cover\%s" % (i)
mediaType = "image"
myMedia.uplaod(accessToken, filePath, mediaType,i)