Alister West

home is where your code is ...

Mojolicious - Serve static file.

Mojolicious has the 'static' helper for dealing with objects in your 'public' directory. This recipe does the same thing but with a bit more control, allowing you to serve from any location and as anyname.

#!/usr/bin/env perl
use Mojolicious::Lite;

# Serve '/tmp/foo_123456.txt' at '' as ''

get '/123' => sub {
    my $self = shift;

    # Do things that mean you can't serve this file out of $root/public
    # eg. save download stats, lock file in db to $session->user, etc.

    my ($path, $file, $new_name) = ('/tmp', 'foo_123456.txt', '');

    # Setup static file handler - or use $self->app->static
    use Mojolicious::Static;
    my $static = Mojolicious::Static->new( paths => [ $path ] );

    # Tell browser to save file as a different name.
    $self->res->headers->content_disposition qq{'attatchment; filename="$new_name"'};

    # Send
    $static->serve($self, $file);

By Alister West