I design a simple form which uses the post method to send the picture to the server. However the post handler only catches the filename and can not save the image.
Following is the header that receives and the html -python code
<!DOCTYPE html>
<html>
<head>
<title>Using Python's SimpleHTTPServer Module</title>
</head>
<body>
<div>
<h1>The input accept attribute</h1>
<form action="/upload" method="post" enctype="application/x-www-form-urlencoded">
<label for="img">Select image:</label>
<input type="file" id="img" name="img" accept="image/*">
<input type="submit">
</form>
</div>
<div id="uploadedImage"></div>
</body>
</html>
python code
from http.server import BaseHTTPRequestHandler, HTTPServer, SimpleHTTPRequestHandler, test
from urllib.parse import urlparse
from urllib.parse import parse_qs
from functools import partial
from io import BytesIO
import cgi,json
import base64
import os
hostName = "localhost"
serverPort = 80
def SELECT_FILE(filename, show=False):
import os
here = os.path.dirname(os.path.abspath(__file__))
add=os.path.join(here,filename)
if(show):print(add)
return add
class MyServer(SimpleHTTPRequestHandler):
"""Main class to present webpages and authentication."""
counter=0
def __init__(self, *args, **kwargs):
username = kwargs.pop("username")
password = kwargs.pop("password")
directory = kwargs.pop("directory")
self._auth = base64.b64encode(f"{username}:{password}".encode()).decode()
self.counter=0
print("initiate")
super().__init__(*args, **kwargs)
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_AUTHHEAD(self):
self.send_response(401)#the client request has not been completed because it lacks valid authentication credentials for the requested resource
self.send_header("WWW-Authenticate", 'Basic realm="Test"')
self.send_header("Content-type", "text/html")#tells the browser, the type of response it is getting from the server.
self.end_headers()
type(self).counter = type(self).counter + 1
def load_binary(self,filename):
with open(SELECT_FILE(filename), 'rb') as file_handle:
return file_handle.read()
def parseQuery(self):
if self.path.find('?') > -1:
query = self.path.split('?')[1]
return {key: value for [key, value] in map(lambda x: x.split('='), query.split('&'))}
else:
return {}
def do_GET_Auth(self): # process authenticated get request
if self.path == '/':
#self.path = 'index.html' #/
self.wfile.write(self.load_binary('index.html'))
return
elif self.path.startswith('/process'):
qdic=self.parseQuery()
self.send_text_respond(qdic["key"])
else:
super().do_GET()
def do_PIC(self,path_to_image):
file_info = os.stat(path_to_image)
img_size=file_info.st_size
self.send_response(200)
self.send_header("Content-type", "image/jpg")
self.send_header("Content-length", img_size)
self.end_headers()
f = open(path_to_image, 'rb')
self.wfile.write(f.read())
f.close()
def do_GET(self): # first do the Authorization
if self.headers.get("Authorization") == None:
self.do_AUTHHEAD()
self.wfile.write(b"no auth header received when logon cancel buttom pressed")
elif self.headers.get("Authorization") == "Basic " + self._auth:
self.do_GET_Auth()
else:
self.do_AUTHHEAD()
self.wfile.write(self.headers.get("Authorization").encode())
self.wfile.write(b"not authenticated")
def do_POST(self):
# Host: localhost
# Connection: keep-alive
# Cache-Control: max-age=0
# Authorization: Basic YWRtaW46YWRtaW4=
# Origin: http://localhost
# Content-Length: 23
# Content-Type: application/x-www-form-urlencoded
content_length = int(self.headers['Content-Length'])
file_content = self.rfile.read(content_length) #img=IMG_20230107_221530_264.jpg
print(content_length,'\n',self.path,'\n',file_content .decode("utf-8"),'\n')#,urlparse(self.path)
#/upload [name ,value]
# message=%0D%0A++++++++++hvjh
# &idz=145198
# &send_messageZ=Send
self.send_response(200)
self.send_header("Content-type", "image/jpg")
self.send_header("Content-length", content_length)
self.end_headers()
self.wfile.write( file_content )
return
def send_text_respond(self,txt):
self.send_response(200, 'OK')
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write(txt.encode())
if __name__ == "__main__":
handler_class = partial( MyServer, username='admin',password='admin',directory=os.getcwd(),)
webServer = HTTPServer((hostName, serverPort), handler_class)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")
I'm trying to use the HTTP.server.BaseHTTPRequestHandler library to upload and save the image on the local disk