__author__ = 'asc' def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for http.client connection instance """ BOUNDARY_STR = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = bytes("\r\n","ASCII") L = [] for (key, value) in fields: L.append(bytes("--" + BOUNDARY_STR,"ASCII")) L.append(bytes('Content-Disposition: form-data; name="%s"' % key,"ASCII")) L.append(b'') L.append(bytes(value,"ASCII")) for (key, filename, value) in files: L.append(bytes('--' + BOUNDARY_STR,"ASCII")) L.append(bytes('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename),"ASCII")) L.append(bytes('Content-Type: %s' % get_content_type(filename),"ASCII")) L.append(b'') L.append(value) L.append(bytes('--' + BOUNDARY_STR + '--',"ASCII")) L.append(b'') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=' + BOUNDARY_STR return content_type, body