File Upload

The python scripts in this page and in the next one will try to save an uploaded file in a directory named files in the directory where it is running. If the directory where the script is running is /path/to/dir then the /path/to/dir/files directory must exist otherwise it will fail.

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

The getfirst() and getlist() methods will only return the file(s) content. To also get the filename it is necessary to access a nested Field instance which is indexed by the field name in the FieldStorage instance.

This script is a simplified version of the the one on the next page. This was done for didactic purposes only. Always use the one on the next page.

<html><body>
<%
if form.has_key('file') and form['file'].filename:
   # A nested Field object holds the file
   fileitem = form['file']

   try: # Windows needs stdio set for binary mode.
      import msvcrt
      msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
      msvcrt.setmode (1, os.O_BINARY) # stdout = 1
   except ImportError:
      pass

   # strip leading path from file name to avoid directory traversal attacks
   fname = os.path.basename(fileitem.filename)

   # build absolute path to files directory
   dir_path = os.path.join(os.path.dirname(req.filename), 'files')

   open(os.path.join(dir_path, fname), 'wb').write(fileitem.file.read())
   message = 'The file "%s" was uploaded successfully' % fname
%>
<p><%= message %></p>
<p><a href="">Upload another file</a></p>
<%
else:
   #
%>
<form enctype="multipart/form-data" action="" method="post">
<p>File: <input type="file" name="file"></p>
<p><input type="submit" value="Upload"></p>
</form>
<%
#
%>
</body></html>

A directory traversal attack is one where the attacker submits a file with a leading path like in ../../attacker_program. This way he can save a program wherever the Apache user has write permission. Or read a file if the target script reads files.