[Catalyst] TIP: When file uploads just don't work, try multipart/form-data!

will trillich will.trillich at serensoft.com
Thu Dec 30 05:00:32 GMT 2010


In the hopes of sparing another unfortunate soul from suffering the
wrestling match I've been having this week...


SYMPTOM: Regardless of how many upload-file fields you have in your form,
Catalyst doesn't see the file uploads. That is, *$c->req->uploads* is an
empty hash?! And *$c->req->upload* is an empty array?! File uploads are not
working at all!

Let's say you develop a form that works just fine, and then you add an
upload field. Everything else still works as before, but the uploads are
ignored: *$c->req->uploads* is an empty hash (and *$c->req->upload* is an
empty array). You can see some of the details in *$c->req->_body* but
there's no uploaded info to work with! You can't get the uploaded file from
/tmp/blahblahblah because there isn't any such uploaded file. You can't see
the size or the content or the mime-type. It's as if nothing is uploaded at
all.


SOLUTION: To deal with uploaded files, your form must use "*
multipart/form-data*"! It's not Catalyst's fault, your web browser behaves
differently depending on the <form> attributes you specified. Here's the
primary snippet to add when using HTML::FormHandler...

{
    package MyApp::Form::UploadForm;
    use HTML::FormHandler::Moose;
    extends 'HTML::FormHandler::Model::DBIC';
    with 'HTML::FormHandler::Render::Table';

    has '+item_class' =3D> ( default =3D> 'RecordSpecHere' );

    # MULTIPART/FORM-DATA is MANDATORY for file-uploads, beware!
*    has '+enctype' =3D> ( default =3D> 'multipart/form-data' );*

    has_field 'id'        =3D> ( type =3D> 'Hidden', );
#...
    has_field 'myfile' =3D> ( type =3D> 'Upload' );
}


At any rate, your form tag will now look a bit like this:

<form enctype=3D"*multipart/form-data*" method=3D"*post*" id=3D"form996">

Single-stepping through the Perl debugger will now show that Catalyst has
everything you need in *$c->req->uploads*:

DB<3> *x $c->req->uploads*
0  HASH(0xc54f598)
   'myfile' =3D> Catalyst::Request::Upload=3DHASH(0xc56d858)
      'filename' =3D> 'sample-file.txt'
      'headers' =3D> HTTP::Headers=3DHASH(0xc56d918)
         'content-disposition' =3D> 'form-data; name=3D"myfile";
filename=3D"sample-file.txt"'
         'content-type' =3D> 'application/octet-stream'
      'size' =3D> 74
      'tempname' =3D> '/tmp/BqoVhCmj3f'
      'type' =3D> 'text/plain'

Woo hoo!


-- =

Failure is not important. How you overcome it, is.
-- Nick Vujicic
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.scsys.co.uk/pipermail/catalyst/attachments/20101229/d723d=
073/attachment.htm


More information about the Catalyst mailing list