Handling Binary Content

There are several common text-based content types that you might generate with CGI scripts besides HTML. For example, you might want to send images, audio files, or Zip archives to your users via a CGI program. The first step is to set the content type appropriately—the second step is to send the binary content to the user as the body of the request. Sending a text file is simple, here’s a very short script that will do the trick:

#!/usr/local/bin/perl 
use CGI; 
my $query = new CGI; 
print $query->header(-type=>'text/plain'); 
open (FILE, "< some_file.txt") 
    or die "Can't open some_file.txt"; 
while (<FILE>) { 
    print; 
} 

Sending a binary file to the user is slightly more complex. First, let’s look at a simple script that opens ...

Get Sams Teach Yourself CGI in 24 Hours, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.