I am trying to display an image file in web browser via the Apache server by Python. I am using:
windows 7
apache http server 2.2
python 2.7
Configuration in httpd.conf:
DocumentRoot "C:/Apache2.2/htdocs"
RewriteRule ^images/(.+)$ /imagetest.py?img=$1 [QSA,L]
imagetest.py under htdocs folder :
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
The http://localhost/images/0001.jpg URL gives;
– The image cannot be displayed because it contains errors error at Firefox,
– nothing at Chrome.
But in both cases the image fetched (about 1 MB) with http status code 200 (looked with Firebug).
Any suggestions?
Additionally, is it right way of doing stuff like this way? I decided to use cgi because of this server will serve nothing but images and some video files indirectly (namely via python script). I mean, no complicated operations there. However this server should handle many requests fast and reliable. Thanks.
file.read()is not guaranteed to read the entire file. Useshutil.copyfileobj()to copy the file contents tosys.stdout.Or, better yet, enable and use mod_xsendfile.