20 Enables the use of multipart/form-data for posting forms
23 Upload files in python:
24 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
26 Fabien Seisen: <fabien@seisen.org>
29 import MultipartPostHandler, urllib2, cookielib
31 cookies = cookielib.CookieJar()
32 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
33 MultipartPostHandler.MultipartPostHandler)
34 params = { "username" : "bob", "password" : "riviera",
35 "file" : open("filename", "rb") }
36 opener.open("http://wwww.bobsite.com/upload/", params)
39 The main function of this file is a sample which downloads a page and
40 then uploads it to the W3C validator.
42 from __future__
import print_function
44 from builtins
import object
45 from email.generator
import _make_boundary
49 from io
import StringIO
51 IS_PY2 = sys.version_info[0] == 2
54 from urllib2
import BaseHandler, build_opener, HTTPHandler
56 from urllib.request
import BaseHandler, build_opener, HTTPHandler
61 import urllib.parse
as ulib
73 handler_order = HTTPHandler.handler_order - 10
77 if data
is not None and type(data) != str:
81 for(key, value)
in list(data.items()):
83 v_vars.append((key, value))
85 systype, value, traceback = sys.exc_info()
86 raise TypeError(
"not a valid non-string sequence or mapping object", traceback)
89 data = ulib.urlencode(v_vars, doseq)
93 contenttype =
'multipart/form-data; boundary=%s' % boundary
94 if(request.has_header(
'Content-Type')
95 and request.get_header(
'Content-Type').
find(
'multipart/form-data') != 0):
96 print(
"Replacing %s with %s" % (request.get_header(
'content-type'),
'multipart/form-data'))
97 request.add_unredirected_header(
'Content-Type', contenttype)
99 request.data = bytearray(data,
'latin1')
105 boundary = _make_boundary(os.getuid + os.getpid())
108 for(key, value)
in these_vars:
109 buf.write(
'--%s\r\n' % boundary)
110 buf.write(
'Content-Disposition: form-data; name="%s"' % key)
111 buf.write(
'\r\n\r\n' + value +
'\r\n')
112 for(key, fd)
in files:
113 file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
114 filename = fd.name.split(
'/')[-1]
115 contenttype = mimetypes.guess_type(filename)[0]
or 'application/octet-stream'
116 buf.write(
'--%s\r\n' % boundary)
117 buf.write(
'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
118 buf.write(
'Content-Type: %s\r\n' % contenttype)
121 buf.write(
'\r\n' + fd.read() +
'\r\n')
122 buf.write(
'--' + boundary +
'--\r\n\r\n')
127 https_request = http_request
132 validatorURL =
"http://validator.w3.org/check"
133 opener = build_opener(MultipartPostHandler)
135 def validateFile(url):
136 temp = tempfile.mkstemp(suffix=
".html")
137 os.write(temp[0], opener.open(url).
read())
138 params = {
"ss" :
"0",
139 "doctype" :
"Inline",
140 "uploaded_file" : open(temp[1],
"rb") }
141 print(opener.open(validatorURL, params).
read())
144 if len(sys.argv[1:]) > 0:
145 for arg
in sys.argv[1:]:
148 validateFile(
"http://www.google.com")
150 if __name__==
"__main__":