0

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.

1 Answer 1

2

file.read() is not guaranteed to read the entire file. Use shutil.copyfileobj() to copy the file contents to sys.stdout.

Or, better yet, enable and use mod_xsendfile.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ignacio Vazquez-Abrams, I got rid of all file IO code lines by using mod_xsendfile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.