- 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
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>
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("\", "/" ))
- How to upload file with selenium (Python)?
- How to upload a file in Cypress?
- How to upload a file using JSP?
- How do we do a file upload using Python CGI Programming?
- CSS Styling of File Upload Button with ::file-selector-button Selector
- Cross-browser drag-and-drop HTML file upload?
- How can you upload a file using JSP?
- Upload file with php to another php server
- How to create a file upload button with HTML?
- How to handle windows file upload using Selenium WebDriver?
- File Upload using Selenium WebDriver and Java Robot Class.
- Using header rows during flat file upload in SAP HANA
- Using GUI upload to attach a file to email in SAP
- How to upload a file in Selenium with no text box?
- How to upload a big CSV file in SAP Hybrid mobile app quickly?