Skip to content

Instantly share code, notes, and snippets.

@waltfy
Created July 15, 2025 09:35
Show Gist options
  • Select an option

  • Save waltfy/38e894a350de50def6e8e2390c98d0f7 to your computer and use it in GitHub Desktop.

Select an option

Save waltfy/38e894a350de50def6e8e2390c98d0f7 to your computer and use it in GitHub Desktop.
python-upload
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
import cgi
UPLOAD_DIR = "uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(
b'Upload server is running. Use POST /upload to send a file.')
def do_POST(self):
if self.path != '/upload':
self.send_response(404)
self.end_headers()
self.wfile.write(b'Not found.')
return
content_type = self.headers.get('Content-Type')
if not content_type or 'multipart/form-data' not in content_type:
self.send_response(400)
self.end_headers()
self.wfile.write(b'Invalid content type.')
return
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': self.headers['Content-Type']},
)
if 'file' not in form:
self.send_response(400)
self.end_headers()
self.wfile.write(b'Missing file field.')
return
file_item = form['file']
filename = os.path.basename(file_item.filename)
filepath = os.path.join(UPLOAD_DIR, filename)
with open(filepath, 'wb') as f:
f.write(file_item.file.read())
self.send_response(200)
self.end_headers()
self.wfile.write(
f'File "{filename}" uploaded successfully.\n'.encode())
if __name__ == '__main__':
server_address = ('', 8080)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print("Server running on http://localhost:8080 ...")
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment