Created
November 27, 2023 07:11
-
-
Save 2matzzz/57be6d7e866b84c63559f022c6ff9e61 to your computer and use it in GitHub Desktop.
python3 http post server
This file contains 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
from http.server import BaseHTTPRequestHandler, HTTPServer | |
import os | |
import sys | |
from urllib.parse import unquote | |
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): | |
def do_POST(self): | |
file_name = os.path.basename(unquote(self.path)) | |
if file_name: | |
content_length = self.headers.get('Content-Length') | |
if content_length: | |
content_length = int(content_length) | |
file_data = self.rfile.read(content_length) | |
save_path = os.path.join(os.getcwd(), file_name) | |
with open(save_path, "wb") as output_file: | |
output_file.write(file_data) | |
self.send_response(200) | |
self.end_headers() | |
self.wfile.write(b'File uploaded successfully.') | |
else: | |
self.send_response(411) | |
self.end_headers() | |
self.wfile.write(b'Content-Length header is missing.') | |
else: | |
self.send_response(400) | |
self.end_headers() | |
self.wfile.write(b'Invalid file name.') | |
if __name__ == '__main__': | |
if len(sys.argv) != 3: | |
print("Usage: python3 script.py <Host> <Port>") | |
sys.exit(1) | |
host, port = sys.argv[1], int(sys.argv[2]) | |
httpd = HTTPServer((host, port), SimpleHTTPRequestHandler) | |
print(f"Starting httpd server on {host}:{port}") | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment