Skip to content

Instantly share code, notes, and snippets.

@mic-e
Created April 27, 2023 12:51
Show Gist options
  • Save mic-e/42150a8ff4c854fddd30fc5acb876c7a to your computer and use it in GitHub Desktop.
Save mic-e/42150a8ff4c854fddd30fc5acb876c7a to your computer and use it in GitHub Desktop.
Simple file upload server (equivalent of python3 -m http.server)
#!/usr/bin/env python3
from cgi import parse_header, parse_multipart
from http.server import BaseHTTPRequestHandler, HTTPServer
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(
"""
<!DOCTYPE html><html><body><form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" onchange="this.form.submit();document.body.innerText='uploading';">
</form></body></html>
""".encode(
"utf-8"
)
)
def do_POST(self):
ctype, pdict = parse_header(self.headers["Content-Type"])
if ctype != "multipart/form-data":
return
pdict["boundary"] = pdict["boundary"].encode("utf-8")
data = parse_multipart(self.rfile, pdict)["file"][0]
import tkinter
import tkinter.filedialog
tkinter.Tk().withdraw()
with tkinter.filedialog.asksaveasfile("wb") as wfile:
wfile.write(data)
print(f"{wfile.name!r}: {len(data)} bytes written")
self.send_response(301)
self.send_header("Location", "/")
self.end_headers()
with HTTPServer(("", 8000), handler) as server:
try:
server.serve_forever()
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment