uploading image to server php to python
Question: I am converting my code from php to python and want to find the equivalent in
python. My android application sends a base64 encrypted image and folder name.
The script should decode it and save it to my server.

The php is

    
    
    <?php
        // Get image string posted from Android App
        $base=$_REQUEST['image'];
        // Get file name posted from Android App
        $filename = $_REQUEST['filename'];
        // Decode Image
        $binary=base64_decode($base);
        header('Content-Type: bitmap; charset=utf-8');
        // Images will be saved under 'www/img/uplodedimages' folder
        $file = fopen('/home1/test/public_html/img/'.$filename.'.jpg', 'wb');
        if($file != true)
        {
        echo'Error uploading image';
        }
        else{
         // Create File
        fwrite($file, $binary);
        fclose($file);
        echo 'Image upload successful';
        }
    ?>
    

My attempt to convert to python is bellow

    
    
    #! /usr/bin/python
    import cgi
    import base64
    import json
    
    print "Content-type: text/html\r\n\r\n"
    
    d = {}
    arguments = cgi.FieldStorage()
    base = arguments.getvalue('image')
    filename = arguments.getvalue('filename')   
    
    binary = base.b64decode('base64')
    file = open('/home1/test/public_html/img/%s.jpg', 'wb') % filename
    if file != True:
        d['success'] = 0
        d['message'] = 'Error uploading image'
        print json.dumps(d)
    else:
        file.write(file, binary)
        file.close()
        d['success'] = 1
        d['message'] = 'Upload Successful'
        print json.dumps(d)
    

I have never used I/O With python so I am new with it. When running the output
is blank.


Answer: This should work

    
    
    #! /usr/bin/python
    import cgi
    import base64
    import simplejson
    
    print "Content-type: text/html\r\n\r\n"
    
    d = {}
    arguments = cgi.FieldStorage()
    data = arguments.getvalue('image')
    filename = arguments.getvalue('filename')
    
    binary = base64.b64decode(data)
    file = open('/home1/test/public_html/img/%s.jpg' % filename, 'wb')
    
    if file != True:
        d['success'] = 0
        d['message'] = 'Error uploading image'
        print simplejson.dumps(d)
    else:
        file.write(file, binary)
        file.close()
        d['success'] = 1
        d['message'] = 'Upload Successful'
        print simplejson.dumps(d)
    

