Skip to content

Instantly share code, notes, and snippets.

@jberger
Last active December 30, 2015 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/7853569 to your computer and use it in GitHub Desktop.
Save jberger/7853569 to your computer and use it in GitHub Desktop.
downloaded file saving helpers
package Mojolicious::Plugin::ReceivedFile;
use Mojo::Base 'Mojolicious::Plugin';
use File::Spec;
use Mojo::Util 'monkey_patch';
sub register {
my ($self, $app) = @_;
monkey_patch 'Mojo::Transaction',
filename => \&filename,
savefile => \&savefile;
}
sub filename {
my ($tx) = @_;
my $disp = $tx->res->headers->content_disposition;
if ($disp) {
return $1 if $disp =~ /filename\=\"([^"]+)\"/;
}
my $path = $tx->req->url->path;
unless ($path->trailing_slash) {
return $path->parts->[-1];
}
return;
}
sub savefile {
my ($tx, $dir, $name) = @_;
$dir = File::Spec->rel2abs('.') unless $dir;
$name = filename($tx) unless $name;
my $path = File::Spec->catfile($dir, $name);
print "Saving to $path ...\n";
$tx->res->content->asset->move_to($path);
return $path;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment