File Upload Example in Python

File upload in Python can be implemented using the CGI (Common Gateway Interface) environment. This involves creating an HTML form for file selection and a Python script to handle the server−side file processing.

The file upload process consists of two main components: an HTML form that allows users to select files, and a Python CGI script that processes and saves the uploaded files to the server.

Creating HTML Form for File Upload

The HTML form uses <input type="file"> to create a file selection field and <input type="submit"> for the upload button. The form must include enctype="multipart/form-data" to handle file uploads properly ?

Example

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

Output

File: Choose File No file chosen Upload

Python Script to Handle File Upload

The Python CGI script processes the uploaded file using the cgi module. Key components include ?

  • cgitb.enable() − Activates error reporting for debugging
  • cgi.FieldStorage() − Provides access to form data and uploaded files
  • os.path.basename() − Prevents directory traversal attacks

Example

#!/usr/bin/env python3

# Importing required modules
import cgi
import os
import cgitb

# Enable CGI error reporting
cgitb.enable()

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get the file item from the form
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 the file and write its contents to the server
    with open('/tmp/' + fn, 'wb') as f:
        f.write(fileitem.file.read())
    
    # Success message
    message = f'The file "{fn}" was uploaded successfully'
else:
    # Error message
    message = 'No file was uploaded'

# Print the HTTP headers and HTML content
print(f"""\
Content-Type: text/html\n
<html>
<body>
    <p>{message}</p>
</body>
</html>
""")

Output Examples

When a file is uploaded successfully ?

The file "document.txt" was uploaded successfully

When no file is selected ?

No file was uploaded

Security Considerations

Always use os.path.basename() to prevent directory traversal attacks. Consider implementing file type validation and size limits for production applications.

Conclusion

File uploads in Python using CGI require an HTML form with proper encoding and a Python script using the cgi module. Always implement security measures like path sanitization and file validation for safe file handling.

Updated on: 2026-03-25T07:51:41+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements