tags:

views:

31

answers:

2

Hello,

Is there a way of uploading an image file using python ?. Im able to upload files from a simple html page consisting of the code below.But i would like to be able to do that from a python program. Can it be done using urllib2 module ?. Any example i can refer to ?

Please help. Thank You.

<form action="http://somesite.com/handler.php" method="post" enctype="multipart/form-data">

<table>

        <tr><td>File:</td><td><input type="file" name="file" /></td></tr>

        <tr><td><input type="submit" value="Upload" /></td></tr>

</table>

</form>
A: 

You can use pycurl package for that.

from StringIO import StringIO
from pycurl import *
c = Curl()
d = StringIO()
h = StringIO()
c.setopt(URL, "http://somesite.com/handler.php")
c.setopt(POST, 1)
c.setopt(HTTPPOST, [('file', (FORM_FILE, '/path/to/file')), ('submit', 'Upload')])
c.setopt(WRITEFUNCTION, d.write)
c.setopt(HEADERFUNCTION, h.write)
c.perform()
c.close()
Daniel Kluev