[Catalyst-dev] trouble with a pdf attachment

Octavian Rasnita orasnita at gmail.com
Tue Nov 6 13:41:35 GMT 2012


Hi,

> However, when I try to send back a pdf I get an empty file. 

> sub attach_pdf{
>   my($self, $c, $fileholder, $file, $name) = @_;
> 
>     open(DLFILE, "<$file") or die $c->log->debug("Couldn't open file! $!");


It should better be:

open( my $dlfile, '<', $file ) or die $c->log->debug( "Couldn't open file! $!" );
binmode $dlfile;


 >    my @fileholder = <DLFILE>;

It should better be:

my $fileholder;
{ local $/;
$fileholder = <$dlfile>;
}

The code above could be written to look nicer, but it could have been harder to understand.

The line "local $/;" sets the var $/ to undef in the local scope defined between { and } so the next line slurps the entire file content in the scalar variable $fileholder.

You could have also use instead:

use File::Slurp;
my $fileholder = read_file( $file );


>     close (DLFILE) or die $c->log->debug("Couldn't close file! $!");


It should better be:

close $dlfile or die $c->log->debug( "Couldn't close file! $!" );


>     $c->res->content_type('application/pdf');
>     $c->res->header('Content-Disposition', "attachment; filename=$name");
>     $c->res->body("@$fileholder");

The last line should be:

$c->res->body( $fileholder );
Octavian




More information about the Catalyst-dev mailing list