import httplib mimetypes sys os def post_multipart host selector field

 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
import httplib, mimetypes, sys, os
def post_multipart(host, selector, fields, files):
content_type, body = encode_multipart_formdata(fields, files)
h = httplib.HTTPConnection(host)
headers = {
'User-Agent': 'A2K Image Uploader',
'Content-Type': content_type
}
h.request('POST', selector, body, headers)
res = h.getresponse()
return res.status, res.reason, res.read()
def encode_multipart_formdata(fields, files):
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
if len(sys.argv) < 2:
print "Usage: %s <file to upload>" % sys.argv[0]
raise SystemExit
filename = sys.argv[1]
if not os.path.exists(filename):
print "Error: the file '%s' does not exist" % filename
raise SystemExit
fields=[("public","0")]
files=[("file",filename,open(filename).read())]
host="pic.co.ua"
selector="/index_api.php"
result=post_multipart(host,selector,fields,files);
if result[1]=='OK':
print result[2]
else:
print "Something gone wrong..."