Skip to content

Instantly share code, notes, and snippets.

@Rahmanism
Last active April 17, 2023 06:33
Show Gist options
  • Save Rahmanism/c4be55d58dd2dd6829fc4184348a3ca1 to your computer and use it in GitHub Desktop.
Save Rahmanism/c4be55d58dd2dd6829fc4184348a3ca1 to your computer and use it in GitHub Desktop.
Upload file Python CGI
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