gpt4 book ai didi

python - 如何使用 Python BaseHTTPServerRequestHandler do_GET 方法提供图像内容类型?

转载 作者:太空狗 更新时间:2023-10-30 00:30:35 25 4
gpt4 key购买 nike

我正在使用 BaseHTTPServer 来提供网络内容。我可以提供内容类型“text/html”或“text/css”甚至“text/js”,并在浏览器端呈现。但是当我尝试

self.send_header('Content-type', 'image/png')

对于 .png 文件,它根本不会呈现。

这是一个示例:

                    if self.path.endswith(".js"):
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type', 'text/javascript')
self.end_headers()
self.wfile.write(f.read())
f.close()
return

这对 javascript 非常有用

                    if self.path.endswith(".png"):
f=open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type', 'image/png')
self.end_headers()
self.wfile.write(f.read())
f.close()
return

当我为客户端标记它时,这似乎没有呈现图像内容。它显示为损坏的图像。

有什么想法吗?

最佳答案

您已经以文本模式而不是二进制模式打开了文件。任何换行符都可能被弄乱。改用这个:

f = open(curdir + sep + self.path, 'rb')

关于python - 如何使用 Python BaseHTTPServerRequestHandler do_GET 方法提供图像内容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5287219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com