我正在编写一个小程序,它是一个http服务器,可以列出目录中的每个文件,并使其可在浏览器中预览。当前,它可以列出所有文件和目录,并使它们可导航和预览文本文件。我正在尝试添加jpeg预览功能,但是img元素似乎无法通过其路径找到图像,即使我仍然可以通过单击它们来下载它们。
这是我第一次这样做,所以可能会有很多错误,所以请不要对我太苛刻。 无论如何,这是相关代码:
def getDir(path:str):
f = open(".\\_INTERNAL\\pageTemplate.html","rt")
basePage = f.read()
basePage = basePage.replace("${path}", path.replace("\_CONTENT","").replace("\\","/"))
fileList =""
pathUp = findParentPath(path)
print(pathUp)
print(path)
if(pathUp != ".\\_CONTENT\\"):
fileList +="<a href='{}'>..</a>".format(pathUp.replace(".\_CONTENT","")[:-1])
for name in os.listdir(path):
char = ''
print(path[-1])
if path[-1] != '/':
char = '\\'
if("." not in name):
fileList +="<a class='folder-link' style='display:block' href='{1}'>{0}</a>".format(name, path.replace(".\_CONTENT","")+char+name)
else:
fileList +="<a class='file-link' style='display:block' href='{1}'>{0}</a>".format(name, path.replace(".\_CONTENT","")+char+name)
if(name.split('.')[-1] == 'jpg'):
fileList+="<img alt='{0}' src='{1}' style='display:block'>".format(name, path.replace(".\_CONTENT","")+char+name)
return basePage.replace("${filelist}", fileList)
request = sock.recv(4096).decode()
print(request)
file_to_send = request[request.find("GET /") + len("GET /"):]
file_to_send = file_to_send[:file_to_send.find(" ")]
if file_to_send == "":
file_to_send = "index.html"
file_to_send = file_to_send.replace("%20", " ")
contentType = "*/*"
if os.path.exists(".\\_CONTENT\\" + file_to_send):
if(os.path.isdir(".\\_CONTENT\\" + file_to_send)):
data = getDir(".\\_CONTENT\\" + file_to_send).encode()
else:
if(file_to_send.split('.')[-1] == 'txt'):
data = getTxtFile(".\\_CONTENT\\" + file_to_send).encode()
else:
if(file_to_send.split('.')[-1] == 'jpeg' or 'jpg'):
contentType = 'image/jpeg'
f = open(".\\_CONTENT\\" + file_to_send,"rb")
data = bytes(f.read())
else:
f = open(".\\_INTERNAL\\404.html","rb")
data = bytes(f.read())
headers = """
HTTP/1.1 200 OK
Content-Length: """ + str(len(data)) +"\nContent-Type: "+contentType+ """
Connection: Closed
"""
print(headers)
sock.send((headers + "\n\n").encode() + data)
sock.close()