CGI Downloads: Forcing the Issue
In Example 15-27, we wrote a script named getfile.py, a Python CGI program designed
to display any public server-side file, within a web browser (or other recipient) on the
requesting client machine. It uses a Content type of text/plain or text/html to make
the requested file’s text show up properly inside a browser. In the description, we
compared getfile.py to a generalized CGI download tool, when augmented with cut-
and-paste or save-as interactions.
While true, getfile.py was intended to mostly be a file display tool only, not a CGI
download demo. If you want to truly and directly download a file by CGI (instead of
displaying it in a browser or opening it with an application), you can usually force the
browser to pop up a Save As dialog for the file on the client by supplying the appropriate
Content-type line in the CGI reply.
Browsers decide what to do with a file using either the file’s suffix (e.g., xxx.jpg is
interpreted as an image), or the Content-type line (e.g., text/html is HTML code). By
using various MIME header line settings, you can make the datatype unknown and
effectively render the browser clueless about data handling. For instance, a Content
type of application/octet-stream in the CGI reply generally triggers the standard Save
As dialog box in a browser.
This strategy is sometimes frowned on, though, because it leaves the true nature of the
file’s data ambiguous—it’s usually better to let the user/client decide how to handle
downloaded data, rather than force the Save As behavior. It also has very little to do
with Python; for more details, consult a CGI-specific text, or try a web search on “CGI
download.”
1228 | Chapter 15: Server-Side Scripting