How can I make a Mojolicious::Lite static file downloader?

2.7k Views Asked by At

I'm trying to make a file upload/downloader with Mojolicious::Lite and while the upload section is no problem the download section is causing trouble. This code will let me download small text files but anything else turns into a 0 byte file. Any advice on how to do this right?

get '/download/:file' => sub {
    my $self = shift;
    my $file = $self->param('file');
    $self->res->headers->content_type("application/x-download");
    $self->res->content->asset(Mojo::Asset::File->new(path => "./testdir/$file"));
    $self->rendered;
};
2

There are 2 best solutions below

0
On

Joel Berger posted this little program to start a web server to serve local files, and it works great:

use Mojolicious::Lite;

@ARGV = qw(daemon);

use Cwd;
app->static->paths->[0] = getcwd;

any '/' => sub {
    shift->render_static('index.html');
    };

app->start;
0
On

You can install the plugin Mojolicious::Plugin::RenderFile to make this easy.

plugin 'RenderFile';

get '/download/:file' => sub {
  my $self = shift;
  my $file = $self->param('file');
  $self->render_file('filepath' => "./testdir/$file");
};