File upload by urllib2

M

Michael Foord

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.

I have code that uses a request object to make requests using
urllib2.urlopen (including cookie handling via ClientCookie) - which
means it would be extremely incovenient (including probably not
working without the cookie handling) to have to use httplib. It would
also mean duplicating the code...

I had thought of just adding the headers manually using add_header -
but for multipart data we need boundaries and the suchlike...... Has
anyone done this or know the right incantations to do it ?

Regards,


Fuzzy

http://www.voidspace.org.uk/atlantibots/pythonutils.html
 
J

John J. Lee

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/[email protected]


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
 
M

Michael Foord

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/[email protected]


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


Interesting, I'll give it a try.

Thanks

Fuzzy
http://www.voidspace.org.uk/atlantibots/pythonutils.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,090
Latest member
ActivlifeKetoDiet

Latest Threads

Top