[Catalyst] Download a file - Catalyst Docs 'Cookbook' example doesn't work

Matthew Braid catalyst at mdb.id.au
Thu Nov 11 06:33:36 GMT 2010


Hi all,

Part of the site I'm writing includes the ability to download certain
files. These files can be large, so going from the cookbook method at
http://search.cpan.org/~zarquon/Catalyst-Manual-5.8005/lib/Catalyst/Manual/Cookbook.pod#Forcing_the_browser_to_download_content,
I modified it so that the download code was (chopped down code ahead):

    my $fh = handle_of_file_content(); # Pseudo
    my $filename = $c->stash->{file}->fname;
    $c->res->header('Content-Disposition', qq[attachment;
filename="$filename"]);
    $c->res->body($fh);

According to the docs, this should download the file (the filehandle
should be read chunk by chunk and all will be well). Unfortunately
instead the following happens:

  1) The browser always identifies the content as a "HTML File"
  2) Only a small chunk of the file is actually downloaded.

So I made another change and decided to use the response object's
write method like so:

  my $fh = handle_of_file_content(); # Pseudo
  my $filename = $c->stash->{file}->fname;
  $c->res->header('Content-Disposition', qq[attachment; filename="$filename"]);
  while (defined(my $line = <$fh>)) {
    $c->res->write($line);
  }
  close($fh);

This almost works as well - the browser identifies the file type
correctly, and the whole file is downloaded.

Unfortunately the file has a Catalyst error page appended (the error
is it can't find the default template). I'm assuming this is because
once the action is handled it still goes to the default View and tries
to render a page.

So, am I doing something horribly wrong, or do I just need the magic
words that say "Do not forward to the default view"? I'm hoping the
latter, and I'm hoping it's something blindingly obvious and my brain
is just running slow today.

TIA,
MB



More information about the Catalyst mailing list