Last active
December 30, 2015 16:19
-
-
Save jberger/7853569 to your computer and use it in GitHub Desktop.
downloaded file saving helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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