in reply to Download File using CGI

You can't ouput different files in one response: you're mixing HTML with several files.

You need a HTML link pointing to a cgi:

<a href="download.cgi?file=something">download here</a>
And then in the download.cgi only do the header and file-content:
print <<ENDH; Content-type: application/octet-stream Content-Disposition: attachment; filename: $updated ENDH open FILE,"< /my/file" or die "Can't open: $!"; binmode FILE; local $/ = \10240; while (<FILE>) { print $_; } close FILE;

Replies are listed 'Best First'.
Re: Download File using CGI
by MonkPaul (Friar) on Jun 01, 2005 at 15:26 UTC
    Ok, i have the following code
    #!/usr/bin/perl -w use strict; use warnings; use CGI qw(:standard); use CGI::Carp qw(fatalsToBrowser); my $updated = ""; ## set up the HTML page with the header and title lines print header; # start HTML head print start_html("Download page"); # print title bar with string print <<ENDH; Content-type: application/octet-stream Content-Disposition: attachment; filename: $updated ENDH open FILE,"<updated/$updated" or die "Can't open: $!"; binmode FILE; local $/ = \10240; while (<FILE>) { print $_; } close FILE; print end_html;
    and only
    print('<a href="download.cgi?file=$updated">Download Files here</a>');
    in the other file. Is this right.

    It comes out with an error message, simply $updated not defined. How do i pass the file name and its contents through to this download.cgi script without having to declare it at the top.

    Cheers.

      You're still printing a html header and HTML content before printing the header for the file's content.

      As I said before; you can't mix multiple files in one response - the HTML page is one of those files - the other is the file you want people to download.

      You have several options:

      You print the file's content in the HTML (without the headers, and remember to use escapeHTML() to escape any HTML tags in the file) and people will have to cut & paste to save the content.

      You print the correct headers and the file's content and nothing else and the file can be saved with the correct name when that script is called (if the browser supports the content-disposition header)

      You just link to a static file on the server using a normal <a> tag (by far the easiest, and most efficient).

      As for how to pass the filename (dangerous: you don't want just any file to be downloadable) - see Ovid's CGI course.

      HTTP/CGI is not a perl game. Read the RFC, learn the rules.
        Can you tell me what the hell you are talking about.

        What game?