- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do we do a file upload using Python CGI Programming?
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.
<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>
The result of this code is the following form −
File: Choose file Upload
Here is the script save_file.py to handle file upload −
#!/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) open('/tmp/' + fn, 'wb').write(fileitem.file.read()) message = 'The file "' + fn + '" was uploaded successfully' else: message = 'No file was uploaded' print """\ Content-Type: text/html
<html> <body> <p>%s</p> </body> </html> """ % (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("\", "/" ))
- How to do CGI programming in Python?
- How do we upload external file on a website using HTML forms?
- How do cookies work in Python CGI Programming?
- How to upload a file using JSP?
- How do we insert/store a file into MySQL database using JDBC?
- How do I check whether a file exists using Python?
- How to raise a "File Download" Dialog Box in Python CGI Programming?
- How can you upload a file using JSP?
- How do I copy a file in python?
- How do we specify the buffer size when opening a file in Python?
- How do we compare Python Dates?
- File Upload Example in Python
- How to upload file with selenium (Python)?
- How do you append to a file with Python?
- How do I copy a binary file in Python?