Upload forms--where is the file object?

Hi All,

I’ve been trying to create an upload form page that will take an
uploaded file, and save it to a directory on the server. I’ve tried
following a couple of posts on this list, and the HowTo from here:

http://wiki.rubyonrails.org/rails/pages/HowtoUploadFiles

Here is the code in my view:

<%= start_form_tag ( {:action => “upload”}, { :mulipart => true } ) %>
<%= file_field_tag(“file”) %>
<%= submit_tag “Upload” %>
<%= end_form_tag % >

Seems simple enough, But the problem is the object being passed from the
view in params[:file] is a string object, not a file object, so it won’t
respond to any of the methods from the File class in my controller code.
I get a runtime error saying the method is undefined for a string
object. So my question is if params[:file] is just a string containing
the filename, how do I access the File object and the data in the file?

Thanks in advance for any responses.

Dan wrote:

Hi All,

I’ve been trying to create an upload form page that will take an
uploaded file, and save it to a directory on the server. I’ve tried
following a couple of posts on this list, and the HowTo from here:

http://wiki.rubyonrails.org/rails/pages/HowtoUploadFiles

Here is the code in my view:

<%= start_form_tag ( {:action => “upload”}, { :mulipart => true } ) %>
<%= file_field_tag(“file”) %>
<%= submit_tag “Upload” %>
<%= end_form_tag % >

Seems simple enough, But the problem is the object being passed from the
view in params[:file] is a string object, not a file object, so it won’t
respond to any of the methods from the File class in my controller code.
I get a runtime error saying the method is undefined for a string
object. So my question is if params[:file] is just a string containing
the filename, how do I access the File object and the data in the file?

Thanks in advance for any responses.

There’s actually a thread on this going on right now:

http://www.ruby-forum.com/topic/75360#new

-Ben L.

Hi Dan,

Dan wrote:

I’ve been trying to create an upload form page that will take an
uploaded file, and save it to a directory on the server.

But the problem is the object being passed from the
view in params[:file] is a string object, not a file object,
so it won’t respond to any of the methods from the File
class in my controller code.

Depending on the size of the file being uploaded, it will either come
back
as a string object (if it’s smaller than about 12KB I think) or as a
file
object. Use the code below in your controller to handle both cases.

if params[:file_to_upload].instance_of?(Tempfile)
FileUtils.copy(params[:file_to_upload].local_path,
“#{RAILS_ROOT}/public/#{@filenametouse}”)
else
File.open("#{RAILS_ROOT}/public/#{@filenametouse}",“w”){|f|
f.write(params[:file_to_upload].read)
f.close}
end

hth,
Bill