1 |
use strict; |
2 |
use warnings; |
3 |
|
4 |
=head1 NAME |
5 |
|
6 |
Arh::Action::UploadPicture |
7 |
|
8 |
=cut |
9 |
|
10 |
package Arh::Action::UploadPicture; |
11 |
use base qw/Arh::Action::CreatePicture/; |
12 |
|
13 |
use Data::Dump qw/dump/; |
14 |
use Imager; |
15 |
|
16 |
=head2 take_action |
17 |
|
18 |
=cut |
19 |
|
20 |
my $buf_size = 8192; |
21 |
my $conf = Jifty->config->app('pictures') or die "no pictures"; |
22 |
my $path = $conf->{original_path} or die "no original_path"; |
23 |
my $scale = $conf->{scale} or die "no scale"; |
24 |
|
25 |
sub take_action { |
26 |
my $self = shift; |
27 |
|
28 |
if ( my $fh = $self->argument_value('content') ) { |
29 |
|
30 |
my $filename = scalar( $fh ); |
31 |
$filename =~ s/^.*([\/\\])([^\1]+)$/$2/; |
32 |
|
33 |
if ( $filename !~ m/\.(jpg|jpeg|png|gif|tif|tiff)$/i ) { |
34 |
$self->result->error("unknown file type $filename"); |
35 |
return; |
36 |
} |
37 |
|
38 |
if ( ! -e $path ) { |
39 |
mkdir $path or die "can't create $path: $!"; |
40 |
} |
41 |
|
42 |
# FIXME add check of maximum upload size |
43 |
|
44 |
open(my $fh_out, '>', "$path/$filename" ) or die "can't open $path/$filename: $!"; |
45 |
my $buff = ' ' x $buf_size; |
46 |
while( read($fh, $buff, $buf_size) ) { |
47 |
print $fh_out $buff or die "can't write to $filename: $!"; |
48 |
} |
49 |
close($fh_out) or die "can't close $filename: $!"; |
50 |
|
51 |
warn "## $self take_action resize $filename [", -s "$path/$filename", " bytes]\n"; |
52 |
|
53 |
my $image = Imager->new; |
54 |
$image->read( file => "$path/$filename" ) or die $image->errstr; |
55 |
|
56 |
my $content; |
57 |
|
58 |
my $scaled_image = $image->scale( %$scale ) or die $image->errstr; |
59 |
undef $image; |
60 |
|
61 |
$scaled_image->write( |
62 |
data => \$content, |
63 |
type => 'jpeg', |
64 |
# jpegquality => 95, |
65 |
) or die $scaled_image->errstr; |
66 |
undef $scaled_image; |
67 |
|
68 |
warn "## resized to ",length($content), " bytes..."; |
69 |
|
70 |
$self->argument_value( 'filename' => $filename ); # needed for report_success |
71 |
$self->argument_value( 'content' => $content ); |
72 |
|
73 |
my $id = $self->SUPER::take_action( @_ ); |
74 |
|
75 |
# update database with correct filename (why do I need this?) |
76 |
$self->record->set_filename( $filename ); |
77 |
|
78 |
return $id; |
79 |
|
80 |
} else { |
81 |
$self->result->error("No file uploaded!"); |
82 |
} |
83 |
|
84 |
} |
85 |
|
86 |
=head2 report_success |
87 |
|
88 |
=cut |
89 |
|
90 |
sub report_success { |
91 |
my $self = shift; |
92 |
$self->result->message( 'Uploaded ' . $self->argument_value('filename') . ' [' . length( $self->argument_value('content') ) . ' bytes]' ); |
93 |
warn "## report_success ", dump( $self->result ); |
94 |
} |
95 |
|
96 |
1; |
97 |
|