Sending binary data over CGI

Tim Roberts timr at probo.com
Thu Mar 4 03:07:44 EST 2004


Walter Huf <hufman at cobalty.com> wrote:
>
>Okay, I'm busy making a wonderful cgi program, and everything is working 
>wonderfully so far. I'm using the standard cgi library and the Cookie 
>library and they have been a huge help. Thanks to those who have created 
>them!
>However, if I try to send binary data, like jpgs, through cgi, the data 
>gets corrupted in a very small manner. Whenever my program sends the 
>character 10, it gets converted to character 13+character 10. I found out 
>this only happens when I send data to stdout. If I send the data to a 
>standard file object, it works fine. However, with the stdout, the problem 
>arises.
>...
>Please help me with this problem. It has me stumped.

Really?  This is such a common problem that most Windows Python programmers
encounter it very early in their experiments.

The issue, of course, is that stdout is opened as a text file, not as a
binary file, and we all know that the LF to CR-LF conversion you describe
is part of the normal processing of a text file in Windows.

If you must send binary data through stdout, do this before you start to
write:

  import os
  import msvcrt
  ...
  msvcrt.setmode( stdout.fileno(), os.O_BINARY )
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list