Python / CGI - Upload file attempt returns an empty page
Question: I really searched about 50 related pages but never seen a problem similar to
my problem. When I press the submit button, it calls the script but the script
returns an empty page and I see no file was uploaded. There is no typing error
in my codes, I checked it several times and I really need this code running
for my project. What might be the problem? I am running apache under ubuntu
and my codes are:

html code:

    
    
    <html><body>
    <form enctype="multipart/form-data" action="save_file.py" method="post">
    <p>File: <input type="file" name="file"></p>
    <p><input type="submit" value="Upload"></p>
    </form>
    </body></html>
    

python code:

    
    
    #!/usr/bin/env python
    import cgi, os
    import cgitb; cgitb.enable()
    
    try: #windows needs stdio set for binary mode
        import msvcrt
        msvcrt.setmode (0, os.O_BINARY)
        msvcrt.setmode (1, os.O_BINARY)
    except ImportError:
        pass
    
    form = cgi.FieldStorage()
    
    #nested FieldStorage instance holds the file
    fileitem = form['file']
    
    #if file is uploaded
    if fileitem.filename:
        #strip leading path from filename to avoid directory based attacks
        fn = os.path.basename(fileitem.filename)
        open('/files' + fn, 'wb').write(fileitem.file.read())
        message = 'The file "' + fn + '" was uploaded successfully'
    else:
        message = 'No file was uploaded'
    
    print """\
    Content-Type: text/html\n
    <html><body>
    <p>%s</p>
    </body></html>
    """ % (message,)
    


Answer: I just tested your script, with a few small corrections to the paths to make
it work for me locally. With the paths set correctly, and permissions set
properly, this code does work fine.

Here are the things to make sure of:

  1. In your html file's form properties, make sure you are pointing to the python script that lives in a cgi-bin: `action="/cgi-bin/save_file.py"`. For me, I have a cgi-bin at the root of my web server, and I placed the python script there. It will not work if you are running the script from a standard document location on the web server 

  2. Make sure your save_file.py has executable permissions: `chmod 755 save_file.py`

  3. In your save_file.py, ensure that you are building a valid path to open the file for saving. I made mine absolute just for testing purposes, but something like this: `open(os.path.join('/path/to/upload/files', fn)`

With those points set correctly, you should not have any problems.

