0

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?

salamey
  • 3,633
  • 10
  • 38
  • 71
  • Do you actually have a file on your filesystem named `"http:\\localhost\myproj\pythonchart.png"`? Because `open()` doesn't do HTTP, but your reported error message doesn't match what you *should* be getting. – Wooble Jan 28 '14 at 13:57
  • I changed the file path to the location of my project : "C:\wamp\www\myproj\pythonchart.png" and I still get the same error – salamey Jan 28 '14 at 14:00
  • I have also tried @teferi suggestion but still the same problem :( – salamey Jan 28 '14 at 14:02
  • Can you confirm through other means that `C:\wamp\www\myproj\pythonchart.png` actually exists and is a valid PNG file? – Robᵩ Jan 28 '14 at 16:36

2 Answers2

1

You should try opening in binary mode open('filename', 'rb').read()

Kirill Zaitsev
  • 4,511
  • 3
  • 21
  • 29
0

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?

Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308