无法通过Apache服务器在网页浏览器中显示Python提供的图像

0 投票
1 回答
611 浏览
提问于 2025-04-16 23:03

我正在尝试通过Apache服务器用Python在网页浏览器中显示一个图片文件。我使用的是:
Windows 7
Apache HTTP服务器 2.2
Python 2.7

在httpd.conf中的配置:

DocumentRoot "C:/Apache2.2/htdocs"
RewriteRule ^images/(.+)$       /imagetest.py?img=$1 [QSA,L]

在htdocs文件夹下的imagetest.py

import cgitb; cgitb.enable()
import cgi

form = cgi.FieldStorage()
imgName = form.getvalue("img")
print "Content-type: image/jpeg"
print
print file(r"C:/imageFolder/" + imgName, "rb").read()

# Also tried 
# sys.stdout.write( "Content-type: image/jpeg\n\n" + file("C:/imageFolder/" + imgName, "rb").read() )
# instead of "print"s above

访问http://localhost/images/0001.jpg这个网址时出现了;
- 在Firefox中显示了无法显示图片,因为它包含错误的错误,
- 在Chrome中什么都没有显示。
不过在这两种情况下,图片(大约1MB)都成功获取了,并且HTTP状态码是200(用Firebug查看的)。
有什么建议吗?
另外,这样做是否正确?我决定使用CGI,因为这个服务器只会提供图片和一些间接的视频文件(也就是通过Python脚本)。我的意思是,这里没有复杂的操作。然而,这个服务器应该能够快速可靠地处理很多请求。谢谢。

1 个回答

2

file.read() 并不能保证会把整个文件都读出来。你可以使用 shutil.copyfileobj() 来把文件的内容复制到 sys.stdout

或者,更好的方法是启用并使用 mod_xsendfile

撰写回答