Q:

Download image by Python CGI

I have a Python cgi that converts a svg to a png file, I'd like then to download the converted output to the user's disk.
#the conversion stuff
print "Content-Type: image/png"
print "Content-Disposition: attachment; filename='pythonchart.png'"
print
print open("http:\\localhost\myproj\pythonchart.png").read()

This results in a png file containing ‰PNG.
Any help please?

A:

You are reading binary data from the text-mode stream returned by open(), and writing binary data to the text-mode stdout stream. You must open the file in binary mode, and convert the stdout to binary mode.
import sys
print "Content-Type: image/png"
print "Content-Disposition: attachment; filename='pythonchart.png'"
print

if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
print open("C:\\wamp\\www\\myproj\\pythonchart.png", "rb").read()

Ref: Python 2.x - Write binary output to stdout?

