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

Dear Monks,

I am having a hard time downloading a text file in the correct format from a Apache server (running in Unix).

All I am trying to do is to have a button to download a text file (let us say, 123.inp residing in htdocs folder) from the server. When I click on 'Download Text File' button, it should provide the option to either "Open" or "Save" the file.

Everything works fine except that if I click on 'Open', the file opens as one single line in "NotePad". I know it is because the file is downloaded in "binary" format but I don't know how to fix it. Any suggestion would be of great help

use CGI qw(:standard); use CGI::Carp 'fatalsToBrowser'; my $query = new CGI; print $query->header(); print $query->start_html(); print $query->button( -name => "Download", -value=>"Download Text File", -onclick=> "window.location.href='/123.inp';" ); print $query->end_html();

Replies are listed 'Best First'.
Re: Downloading a Text file from a Unix server (Apace) using CGI
by swares (Monk) on May 03, 2007 at 20:28 UTC
    Try wordpad. Sounds like the file may be in Unix format and Notepad does not recognize the end of line character. Windows uses a different format... or you can use the unix2dos command to convert it.

      Thanks for the response.

      I used the ux2dos unix utility to convert the file to windows readable format and it works fine now.

Re: Downloading a Text file from a Unix server (Apace) using CGI
by almut (Canon) on May 03, 2007 at 21:18 UTC

    You could deliver the file's content "dynamically", and do explicit line endings conversions yourself as required. For example, you could have a generic CGI script, which takes the file name as parameter (e.g. deliver_plain_text.pl?file=123.inp). The CGI would read the file, convert the line endings (s/\n/\r\n/), and write the result to stdout (which apache sends to the browser, as usual). If you don't want to have deliver_plain_text.pl appear in the URL, you could use mod_rewrite to do some rewriting magic for you...   Also, you might want to apply some heuristics to detect whether the client actually is a Windows machine (e.g. by inspecting the User-Agent header), and only do line ending translations in that case.

    Alternatively, you could try to add an Apache output filter for the appropriate type of files, using mod_mime's AddOutputFilter. I'm not aware of a ready-to-use apache filter for just that purpose, but - if performance is not a primary issue - you could use mod_ext_filter to pipe the content through a simple external program, which does s/\n/\r\n/ ...