#!/usr/bin/env python3 # # run server with: # # python3 -m http.server --cgi 8000 # # upload file with: # # echo foobar | curl -F 'arg=@-;filename=bla.txt' http://127.0.0.1:8000/cgi-bin/upload.cgi # # or: # # curl -F 'arg=@blub/bla.txt' http://127.0.0.1:8000/cgi-bin/upload.cgi import cgi from os.path import basename print("Content-Type: text/plain") print() form = cgi.FieldStorage() if "arg" not in form: print("no arg field") exit() fileitem = form["arg"] if not hasattr(fileitem, "file") or not fileitem.file: print("not a file") exit() if not fileitem.filename or fileitem.filename == "-": print("no filename") exit() filename = basename(fileitem.filename) if not filename: print("invalid filename") exit() try: with open(filename, 'wb') as f: while True: data = fileitem.file.read(4096) if not data: break f.write(data) except PermissionError: print("cannot open file for writing") except IsADirectoryError: print("is a directory") except FileNotFoundError: print("path doesn't exist") else: print("uploaded as %s" % filename)