Force a Download Dialog Box

Many Catalyst apps are made to be dynamic, whether the content is related to books, music, maps, or anything in between. Occasionally, you may want to allow users to download a particular file. Right clicking to save a document doesn't always work on Catalyst, especially with how the Paths work.

Below is a (hopefully) simple example. The controller normally loads the misc page with no arguments. But say you wanted to allow users to download a Mac install file (dmg). If a particular was formed and clicked, say misc/test_mac, use the Content-Type and Content-Disposition headers to force a dialog box, and use serve_static_file (from Static::Simple) to fetch the file. Otherwise, the normal misc page will load up.

sub misc :Global {
    my ( $self, $c, $is_test ) = @_ ;
    if (defined $is_test and $is_test eq 'test_mac')
    {
        $c->response->header('Content-Type' => 'application/x-apple-diskimage');
        $c->response->header('Content-Disposition' => 'attachment; filename=testing.dmg');
        $c->response->header('Content-Description' => 'A test file.'); # Optional line
        $c->serve_static_file('root/static/files/testing.dmg');
    }
    else
    {
        $c->stash->{title} = 'Misc. Stuff';
        $c->stash->{template} = 'misc.tt2';
    }
}
My tags:
 
Popular tags:
 
Powered by Catalyst
Powered by MojoMojo Hosted by Shadowcat - Managed by Nordaaker