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

Want to take input via web form, manipulate it, which is text and send it back to the user as a file to download without writing to disk.
#!/usr/bin/perl -w use CGI qw(:standard); print header; print start_html('Download'), h1('Download'), start_form, p, "Feet? ",textfield(-name=>'feet', -size=>5), "Inches? ",textfield(-name=>'inches', -size=>5), p, submit(-value=>'Create File'), end_form, hr; if (param()) { $feet=param('feet'); $inches=param('inches'); $filename=param('feet') . param('inches') . '.txt'; $tape = <<END; It is $feet ft. $inches in. END # print header(-type=> "application/octet-stream", # -charset=>'UTF-8', # -attachment=>$filename); # print $tape, print "Content-Type: application/octet-stream; name=$filename\n"; print "Content-Disposition:attachment; filename=$filename\"\n\n"; print $tape; }

the browser window shows

Content-Type: application/octet-stream; name=53.txt Content-Disposition:attachment; filename=53.txt" It is 5 ft. 3 in.

I haven't been able to get the download part to work however I can see the text by viewing source.

Thanks, Darrell

Replies are listed 'Best First'.
Re: Web form creates txt file and downloads scalar as a file
by Corion (Patriarch) on Mar 13, 2011 at 16:31 UTC

    You should output proper HTTP headers instead of what you're printing.

    For a start, HTTP headers are delimited by \r\n, not \n alone. Also, you might need to output a HTTP 200 OK status code.

Re: Web form creates txt file and downloads scalar as a file
by wind (Priest) on Mar 13, 2011 at 16:31 UTC

    Only send back one header at a time. Test for request_method eq to POST and then send back the file.

    Like the following:

    #!/usr/bin/perl -w use CGI qw(:standard); use strict; if (request_method() ne 'POST') { print header; print start_html('Download'), h1('Download'), start_form, p, "Feet? ", textfield(-name => 'feet', -size => 5), "Inches? ", textfield(-name => 'inches', -size => 5), p, submit(-value => 'Create File'), end_form, hr, end_html(); } else { my $feet = param('feet'); my $inches = param('inches'); my $filename = param('feet') . param('inches') . '.txt'; my $tape = <<"END_FILE"; It is $feet ft. $inches in. END_FILE print "Content-Type: application/octet-stream; name=$filename\n"; print "Content-Disposition:attachment; filename=$filename\n\n"; print $tape; }

    Also, please use strict.