Last active
April 17, 2023 06:33
-
-
Save Rahmanism/c4be55d58dd2dd6829fc4184348a3ca1 to your computer and use it in GitHub Desktop.
Upload file Python CGI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, cgi, shutil | |
from sys import exit | |
print('Content-Type: text/html') | |
print('') | |
print('<html><body>') | |
# Define the HTML form to upload the file | |
form = cgi.FieldStorage() | |
# Check if the file was uploaded | |
if 'file1' in form: | |
# Get the filename and contents of the uploaded file | |
file_item = form['file1'] | |
filename = os.path.basename(file_item.filename) | |
# check for executable files, to prevent uploading dangerous files. | |
not_allowed_files = ['.py', '.exe', '.cs', '.asp', '.php', '.com', '.js', '.pl'] | |
for ending in not_allowed_files: | |
if (filename.lower().endswith(ending)): | |
print('<h3>This file type is not allowed.</h3>') | |
exit() | |
file_path = os.path.join('./upload/', filename) | |
with open(file_path, 'wb') as file: | |
file.write(file_item.file.read()) | |
print(f"File '{filename}' uploaded successfully.<br />") | |
print(f'<a href="/upload/{filename}" target="_blank">{filename}</a><br />') | |
print('<a href="#" onclick="window.history.go(-1); return false;">Back</a>') | |
else: | |
# If the file was not uploaded, show an error message | |
print("Error: No file was uploaded.") | |
print('</body></html>') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment