File upload by urllib2

John J. Lee jjl at
Mon Sep 13 22:08:45 CEST 2004

fuzzyman at (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:

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)

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


More information about the Python-list mailing list