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

标签 python basehttpserver

我正在使用 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/

相关文章:

python - 在 BaseHTTPServer 中启动守护进程

python - 在 Python 中从 BaseHTTPServer 下载带有 unicode 字符的文件

python - 在mysql中定期向表中添加数据

python - "while not EOF"在 Python 中的完美对应物是什么

python:检查jpg的url是否存在

来自文件的 Python 正则表达式表创建器

http - 为什么 do_GET 比 do_POST 快得多

Python BaseHTTPRequestHandler : Respond with JSON

python - 将参数传递给 SimpleHTTPRequestHandler

python - 使用 SQLAlchemy 元数据 reflect() 如何获得实际的表对象?