File upload by urllib2

John J. Lee jjl at pobox.com
Mon Sep 13 16:08:45 EDT 2004


fuzzyman at gmail.com (Michael Foord) writes:

> Does anyone know how to do a 'file upload' using urllib2 ? 
> There is an example of doing file upload using httplib - on
> activestate python cookbook.
[...]

Actually, more relevant than my previous post:

http://www.google.com/groups?threadm=cpa4qmi9h3i.fsf%40cabernet.nelson.monkey.org


Modifying the recipe that's pointed to from that thread very slightly
for urllib2 (untested!):

def post_multipart(url, fields, files):
    content_type, body = encode_multipart_formdata(fields, files)
    headers = {'Content-type': content_type,
               'Content-length': str(len(body))}
    req = urllib2.Request(selector, body, headers)
    r = urllib2.urlopen(req)
    return r.file.read()


If you get trouble, note my comment in that thread about bad servers.



John



More information about the Python-list mailing list