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 'http://myapp.com/123' as 'random-file.foo'
#

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', 'random-file.foo');

    # 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);
    $self->rendered;
};

app->start;
By Alister West