Kent Johnson escreveu:
> Paulino wrote:
>> Hello!
>>
>>
>> How can I upload a file from python?
>>
>> If it is a form to fill with values it's simple:
>>
>>
>> urlopen("http://site.com/action?key1=value1;key2=value2";) and I get 
>> the form filled.
>>
>>
>> What about uploading a file programmaticaly?
>
> This might help:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
>
> Kent
>
>

Thank You very much Luke, Alan, David and Kent.


I used Nokia's forum recipe (sugested by David) it's very simple and 
works perfectly!

here is it (a few variables changed)


import httplib, urllib
import base64, os.path
 
 
def uploadToURL( aPath ):
    # read the binary data of the pdf
    data = open(aPath, 'rb').read()
    # encoded it to base64
    encodedData = base64.encodestring( data )
    headers = { "Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/plain"  }
 
    params = urllib.urlencode({ 'filename': os.path.split(aPath)[1],
                                'file_data':encodedData})
 
    conn = httplib.HTTPConnection( "localhost:8080" )
    conn.request( "POST", "/rendas/rec/uploadtxt", params, headers )
    response = conn.getresponse( )
    # returns "True" or "False" if failed
    print response.read( )
    # status for debugging
    #print response.status
    conn.close( )
 
 
if __name__ == "__main__":
    uploadToURL("/home/paulino/ola230.pdf")




And here is the turbogears server method that handles the file:


    @expose()
    def uploadtxt(self, file_data, **kw):
        data = base64.decodestring(file_data)
        f = open(kw['filename'], 'wb')
        f.write(data)
        f.close()
        return "Success"
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to