How do we do a file upload using Python CGI Programming?

PythonServer Side ProgrammingProgrammingCGI

To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a "Browse" button.


   <form enctype = "multipart/form-data"
                     action = "" method = "post">
   <p>File: <input type = "file" name = "filename" /></p>
   <p><input type = "submit" value = "Upload" /></p>


The result of this code is the following form −

File: Choose file

Here is the script to handle file upload −

import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
   # strip leading path from file name to avoid
   # directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   open('/tmp/' + fn, 'wb').write(
   message = 'The file "' + fn + '" was uploaded successfully'
   message = 'No file was uploaded'
print """\
Content-Type: text/html\n
""" % (message,)

If you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine.

fn = os.path.basename(fileitem.filename.replace("\\", "/" ))

Published on 31-Jan-2018 13:00:30