Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I was trying to download a file using my CGI script, it's geting downloaded but I am not getting the actual file content ... means after saving the file ... when I open it I don't see the actual content .. instead I see the converted html of my script written into the file.Below is the code

print $cgi->header(-type=>'application/octet-stream',-expires=>'+2m',- +charset=>'UTF-7',-attachment=>'booklist.csv'); print $cgi->start_html(); print $cgi->b("Thanks for downloading the file"); print $cgi->end_html();

I am using perl on windows and IE browser. Any idea why it's behaving so? Thanks for your help in advance.

Replies are listed 'Best First'.
Re: downloading file with CGI
by almut (Canon) on Dec 02, 2009 at 19:38 UTC

    There's nothing magic about the -attachment header — it's just a hint to the browser to prompt the user to save the content sent by the CGI script (instead of displaying it). But you still have to send the content, i.e. read booklist.csv and print it to STDOUT...

      well,if I read from file and print it to STDOUT (as suggested) then it prints to the browser itself and dont prompt for download.

        You have to do both, i.e. use the -attachment header and print the content.  The header tells the browser to prompt with "Save [as...]", using the suggested filename as default.

Re: downloading file with CGI
by zentara (Cardinal) on Dec 03, 2009 at 13:08 UTC
      Hi,

      I got it. It's working fine now. Thanks almut for the suggestion, it worked, but in this case I need to do double task ...

      .

      1. pulled data into the file and save it. 2. again read the data and print it to STDOUT .. for the download purpose.

      Instead if I go for anchor tag

      print $cgi->a({-href=>"filename to download","some text"});
      I directly download the file upon clicking the link

      Thanks again to you all for your help