title: Serving binary file from web server to client
body: <p>Usually, when I want to transfer a web server text file to client, here is what I did</p>
  
  <pre><code>import cgi
  
  print "Content-Type: text/plain"
  print "Content-Disposition: attachment; filename=TEST.txt"
  print
  
  filename = "C:\\TEST.TXT"
  f = open(filename, 'r')
  for line in f:
      print line
  </code></pre>
  
  <p>Works very fine for ANSI file. However, say, I have a binary file <code>a.exe</code> (This file is in web server secret path, and user shall not have direct access to that directory path). I wish to use the similar method to transfer. How I can do so?</p>
  
  <ul>
  <li>What content-type I should use?</li>
  <li>Using print seems to have corrupted content received at client side. What is the correct method?</li>
  </ul>
  
  <p>I use the following code.</p>
  
  <pre><code>#!c:/Python27/python.exe -u
  
  import cgi
  
  print "Content-Type: application/octet-stream"
  print "Content-Disposition: attachment; filename=jstock.exe"
  print
  
  filename = "C:\\jstock.exe"
  f = open(filename, 'rb')
  for line in f:
      print line
  </code></pre>
  
  <p>However, when I compare the downloaded file with original file, it seems there is an extra whitespace (or more) for after every single line.</p>
  
  <p><img src="https://i.stack.imgur.com/bcM8P.png" alt="alt text"></p>