Robert Klemme
10/27/2003 9:43:00 AM
"David Heinemeier Hansson" <david@loudthinking.com> schrieb im Newsbeitrag
news:8A17F0F6-07C3-11D8-BF8E-000A958E6254@loudthinking.com...
> I'm trying to build a form that includes both regular form fields, such
> as text inputs and checkboxes, along with file uploading. It seems,
> though, that all the fields are treated like a File when a file input
> is used. I've tried to narrow it down with this script:
>
> require 'CGI'
> cgi = CGI.new
>
> if cgi.params.length == 0
> print "<html><body><form method='post'
> enctype='multipart/form-data'>"
> print "<input type='text' name='title'><input type='file'
> name='logo'><input type='submit'>"
> print "</form></body></html>"
> else
> $stderr << cgi.params['title'].first
> $stderr << cgi.params['logo'].first.original_filename
> end
>
> Entering "A picture" in the title input and choosing a file called
> "123.jpg" would add the following to the log: "A picture123.jpg".
> Instead I get "#<File:0x40b7e8>123.jpg".
>
> Entering "A picture" in the title input and not choosing a file
> produces:
> #<StringIO:0x209a52c>#<StringIO:0x20b3f04>
>
> I'm baffled. Why is the title input treated first as a file and since
> as a StringIO? I reckon it has something to do with the enctype, but I
> can't seem to come up with a solution.
>
> How would one go about extracting regular form data alongside file
> handling?
>
> Note, I'm using mod_ruby 1.1.1, Apache 1.3.x, and Ruby 1.8.0 on OS X
> 10.3.
If you are using 'multipart/form-data' - which you have to if you want to
upload files via HTTP - all your data (files and input field content) is
sent in a single stream that contains all the data - file content mixed
with field content. I guess the CGI lib just decodes and copies all
content into a series of tmp files if it encounters 'multipart/form-data'
with the optimization that StringIO instances are used if the amount
doesn't get too big (or nor files are used).
In short, you'll have to read all content (file as well as field) as if
reading from an IO if you use 'multipart/form-data'. That's the simples
solution IMHO.
Regards
robert