Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do we do a file upload using Python CGI Programming?
To upload a file using Python CGI programming, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with file type creates a "Browse" button that allows users to select files from their system.
HTML Upload Form
First, create an HTML form that allows file selection ?
<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>
This form displays a file selection interface ?
File: Choose file Upload
Python CGI Upload Handler
Here's the save_file.py script that processes the uploaded file ?
#!/usr/bin/python
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)
# Write file to server
with open('/tmp/' + fn, 'wb') as f:
f.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,))
Cross-Platform File Handling
For Windows systems, you may need to handle backslashes in file paths ?
# Handle Windows file paths
fn = os.path.basename(fileitem.filename.replace("", "/"))
Key Components
| Component | Purpose | Required |
|---|---|---|
enctype="multipart/form-data" |
Enables file uploads in HTML form | Yes |
cgi.FieldStorage() |
Parses form data in Python | Yes |
os.path.basename() |
Security - strips directory paths | Recommended |
cgitb.enable() |
Shows detailed error messages | For debugging |
Conclusion
File uploads in Python CGI require multipart/form-data encoding and cgi.FieldStorage() to process uploads. Always use os.path.basename() for security to prevent directory traversal attacks.
Advertisements
