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 future
import standard_library
45 standard_library.install_aliases()
46 from builtins
import object
47 from email.generator
import _make_boundary
51 from io
import StringIO
53 IS_PY2 = sys.version_info[0] == 2
56 from urllib2
import BaseHandler, build_opener, HTTPHandler
58 from urllib.request
import BaseHandler, build_opener, HTTPHandler
63 import urllib.parse
as ulib
75 handler_order = HTTPHandler.handler_order - 10
79 if data
is not None and type(data) != str:
83 for(key, value)
in list(data.items()):
85 v_vars.append((key, value))
87 systype, value, traceback = sys.exc_info()
88 raise TypeError(
"not a valid non-string sequence or mapping object", traceback)
91 data = ulib.urlencode(v_vars, doseq)
95 contenttype =
'multipart/form-data; boundary=%s' % boundary
96 if(request.has_header(
'Content-Type')
97 and request.get_header(
'Content-Type').
find(
'multipart/form-data') != 0):
98 print(
"Replacing %s with %s" % (request.get_header(
'content-type'),
'multipart/form-data'))
99 request.add_unredirected_header(
'Content-Type', contenttype)
101 request.data = bytearray(data,
'latin1')
107 boundary = _make_boundary(os.getuid + os.getpid())
110 for(key, value)
in these_vars:
111 buf.write(
'--%s\r\n' % boundary)
112 buf.write(
'Content-Disposition: form-data; name="%s"' % key)
113 buf.write(
'\r\n\r\n' + value +
'\r\n')
114 for(key, fd)
in files:
115 file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
116 filename = fd.name.split(
'/')[-1]
117 contenttype = mimetypes.guess_type(filename)[0]
or 'application/octet-stream'
118 buf.write(
'--%s\r\n' % boundary)
119 buf.write(
'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
120 buf.write(
'Content-Type: %s\r\n' % contenttype)
123 buf.write(
'\r\n' + fd.read() +
'\r\n')
124 buf.write(
'--' + boundary +
'--\r\n\r\n')
129 https_request = http_request
134 validatorURL =
"http://validator.w3.org/check"
135 opener = build_opener(MultipartPostHandler)
137 def validateFile(url):
138 temp = tempfile.mkstemp(suffix=
".html")
139 os.write(temp[0], opener.open(url).
read())
140 params = {
"ss" :
"0",
141 "doctype" :
"Inline",
142 "uploaded_file" : open(temp[1],
"rb") }
143 print(opener.open(validatorURL, params).
read())
146 if len(sys.argv[1:]) > 0:
147 for arg
in sys.argv[1:]:
150 validateFile(
"http://www.google.com")
152 if __name__==
"__main__":