我需要一些关于我的以下处理程序的帮助:
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_HEAD(client):
client.send_response(200)
client.send_header("Content-type", "text/html")
client.end_headers()
def do_GET(client):
if client.path == "/":
client.send_response(200)
client.send_header("Content-type", "text/html")
client.end_headers()
client.wfile.write(load('index.html'))
def load(file):
with open(file, 'r') as file:
return encode(str(file.read()))
def encode(file):
return bytes(file, 'UTF-8')
我明白了,函数 load()
是文件中的其他人。通过我的 HTTP 处理程序发送 HTML 页面似乎可行,但我如何发送图像?我需要如何对其进行编码以及我应该使用什么 Content-type
?
非常感谢您的帮助!
(PS:如果我连接到我的 http 服务器,我希望在浏览器中看到发送的图像)
最佳答案
对于 PNG 图像,您必须将内容类型设置为“图像/png”。对于 jpg:“图像/jpeg”。
可以找到其他内容类型 here .
编辑:是的,我在第一次编辑时忘记了编码。
答案是:你不知道!当您从文件加载图像时,它已经采用了正确的编码。
我读到了你的编解码器问题:问题是,正如我在你的加载函数中看到的那样。不要尝试对文件内容进行编码。
对于二进制数据你可以这样使用:
def load_binary(filename):
with open(filename, 'rb') as file_handle:
return file_handle.read()
关于image - 如何编码图像以通过 Python HTTP 服务器发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28567733/