1 package Catalyst::Request::Upload;
4 with 'MooseX::Emulate::Class::Accessor::Fast';
6 use Catalyst::Exception;
8 use IO::File qw( SEEK_SET );
11 has filename => (is => 'rw');
12 has headers => (is => 'rw');
13 has size => (is => 'rw');
14 has tempname => (is => 'rw');
15 has type => (is => 'rw');
16 has basename => (is => 'ro', lazy_build => 1);
25 my $fh = IO::File->new($self->tempname, IO::File::O_RDONLY);
26 unless ( defined $fh ) {
27 my $filename = $self->tempname;
28 Catalyst::Exception->throw(
29 message => qq/Can't open '$filename': '$!'/ );
38 my $basename = $self->filename;
39 $basename =~ s|\\|/|g;
40 $basename = ( File::Spec::Unix->splitpath($basename) )[2];
41 $basename =~ s|[^\w\.-]+|_|g;
49 Catalyst::Request::Upload - handles file upload requests
53 my $upload = $c->req->upload('field');
66 To specify where Catalyst should put the temporary files, set the 'uploadtmp'
67 option in the Catalyst config. If unset, Catalyst will use the system temp dir.
69 __PACKAGE__->config( uploadtmp => '/path/to/tmpdir' );
75 This class provides accessors and methods to handle client upload requests.
83 =head2 $upload->copy_to
85 Copies the temporary file using L<File::Copy>. Returns true for success,
88 $upload->copy_to('/path/to/target');
94 return File::Copy::copy( $self->tempname, @_ );
99 Opens a temporary file (see tempname below) and returns an L<IO::File> handle.
101 =head2 $upload->filename
103 Returns the client-supplied filename.
105 =head2 $upload->headers
107 Returns an L<HTTP::Headers> object for the request.
109 =head2 $upload->link_to
111 Creates a hard link to the temporary file. Returns true for success,
114 $upload->link_to('/path/to/target');
119 my ( $self, $target ) = @_;
120 return CORE::link( $self->tempname, $target );
125 Returns the size of the uploaded file in bytes.
127 =head2 $upload->slurp
129 Returns a scalar containing the contents of the temporary file.
131 Note that this method will cause the filehandle pointed to by
132 C<< $upload->fh >> to be seeked to the start of the file,
133 and the file handle to be put into binary mode.
138 my ( $self, $layer ) = @_;
145 my $handle = $self->fh;
147 binmode( $handle, $layer );
149 $handle->seek(0, SEEK_SET);
150 while ( $handle->sysread( my $buffer, 8192 ) ) {
154 $handle->seek(0, SEEK_SET);
158 =head2 $upload->basename
160 Returns basename for C<filename>.
162 =head2 $upload->tempname
164 Returns the path to the temporary file.
168 Returns the client-supplied Content-Type.
176 Catalyst Contributors, see Catalyst.pm
180 This library is free software. You can redistribute it and/or modify
181 it under the same terms as Perl itself.
185 __PACKAGE__->meta->make_immutable;