
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
File Upload Example in Python
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>
Output
The result of this code is the following form −
Above example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server.
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\n <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("\", "/" ))
- Related Articles
- How to upload file with selenium (Python)?
- How to upload a file in Cypress?
- How do we do a file upload using Python CGI Programming?
- How to upload a file using JSP?
- CSS Styling of File Upload Button with ::file-selector-button Selector
- Cross-browser drag-and-drop HTML file upload?
- Upload file with php to another php server
- How can you upload a file using JSP?
- How to upload file without form using JavaScript?
- Using header rows during flat file upload in SAP HANA
- How to handle windows file upload using Selenium WebDriver?
- How to create a file upload button with HTML?
- File Upload using Selenium WebDriver and Java Robot Class.
- Using GUI upload to attach a file to email in SAP
- How to upload a file in Selenium with no text box?

Advertisements