in reply to Re^4: Correct Perl settings for sending zipfile to browser
in thread Correct Perl settings for sending zipfile to browser
The IO::Compress::Zip docs say you can pass a reference to a scalar to get the data written there. This will use more memory, but here's an example that includes the Content-Length header:
#!/usr/bin/perl use warnings; use strict; use CGI::Simple; use IO::Compress::Zip qw/$ZipError/; use Encode qw/encode/; my @lines = (qw/ Hello World Foo Bar /, "\N{U+1F42A}"); my $CRLF = "\r\n"; my $encoding = "UTF-8"; # or maybe "CP1252" for Windows my $zipdata; my $z = IO::Compress::Zip->new(\$zipdata, Name => "Filename.txt" ) or die "zip failed: $ZipError\n"; for my $line (@lines) { $z->print( encode($encoding, $line.$CRLF, Encode::FB_CROAK|Encode::LEAVE_SRC) ); } $z->close(); my $q = CGI::Simple->new(); print $q->header( -type => 'application/zip', -Content_Disposition => qq{attachment; filename="Download.zip"}, -Content_Length => length($zipdata) ); binmode STDOUT; # just to play it safe print $zipdata;
As for the code you showed, I'd strongly recommend proper indentation (perltidy can help with that). I also have the feeling that you might not be using strict and warnings, or that you're using too many global variables (e.g. $statement). And a nitpick: I wouldn't use $CRLF for outputting the HTTP headers, "\n" is enough, every webserver I've worked with understands that (but really, you should be using a module to write the headers anyway, as I showed above).
Also, as I mentioned, you can save the memory of the @resp array by merging those two loops. For example:
$z->print( encode( $encoding, "RECORD#\tREVISION#\tBOOK#\tCHAP#\tVERSE +#\tTEXT, AS EDITED BY: $curdate $curtime (Pacific Time)$CRLF", Encode +::FB_CROAK|Encode::LEAVE_SRC ) ); while ( ( $recnum, $revnum, $book, $chap, $verse, $text ) = $quest->fe +tchrow_array() ) { $z->print( encode( $encoding, "$recnum\t$revnum\t$book\t$chap\t$ve +rse\t$text$CRLF", Encode::FB_CROAK|Encode::LEAVE_SRC ) ); }
If any of the fields you're outputting could possibly contain tabs, you might want to switch to Text::CSV for proper handling of all of those complexities.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Correct Perl settings for sending zipfile to browser
by Anonymous Monk on Nov 17, 2019 at 21:03 UTC | |
by haukex (Archbishop) on Nov 17, 2019 at 21:28 UTC | |
by Anonymous Monk on Nov 17, 2019 at 22:01 UTC | |
by haukex (Archbishop) on Nov 17, 2019 at 22:23 UTC | |
by Anonymous Monk on Nov 18, 2019 at 08:18 UTC |