Repost a piece of PythonCodeUsing urllib2 to use multipart/form-data to send files
Import httplib, mimetypesdef post_multipart (host, selector, fields, files ): """ Post fields and files to an HTTP host As Multipart/form- Data. 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 the server ' S response page. """ Content_type, body = Encode_multipart_formdata (fields, files) h = Httplib. HTTP (host) H. putrequest ( ' Post ' , Selector) H. putheader ( ' Content-Type ' , Content_type) H. putheader ( ' Content-Length ' , STR (LEN (body) H. endheaders () H. Send (body) errcode, errmsg, headers = H. getreply () Return H. file. Read () 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) ElementsFor Data to be uploaded As Files return (content_type, body) Ready For Httplib. Http instance """ 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, bodydef get_content_type (filename ): Return Mimetypes. guess_type (filename )[ 0 ] Or ' Application/octet-stream '
We recommend that youHttplib. HTTPChange to httplib. httpconnection.When httplib. Connection is initialized, a timeout is input to achieve more flexible control.
See
http://code.activestate.com/recipes/146306/
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2