Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading file in Rails gives String filename instead of File or StringIO object

Rails 3, JRuby 1.6.7.2

I've been trying something "elementary", just uploading a single text file via a form for processing in my app. The problem I'm seeing is that instead of a StringIO or File, I'm getting just a string of the file name.

Here's the form code

= form_tag(:controller => "api/#{CURRENT_API_VERSION}/api", :action => 'file', :method=> :post, :multipart => true) do
    = label_tag "file"
    = file_field_tag "upload[file]"
    = submit_tag 'Analyze!'

And the controller code that is just giving me @upload as a string containing the file name.

def file
        @upload = params[:upload][:file]
        render :template => 'api/file.html.haml'
      end

Running debugger in the controller gives me @upload.class = String, and it doesn't respond to any file or StringIO methods, such as read.

like image 296
will_d Avatar asked Aug 10 '12 05:08

will_d


1 Answers

Found the answer here. It turns out I was just screwing up the form_tag method call. You need to separate the options that are meant for "url_for" and the other options, specifically the multi-part option.

So the correct code for the form is:

= form_tag({:controller => "api/#{CURRENT_API_VERSION}/api", :action => 'file', :method=> :post}, {:multipart => true}) do
    = label_tag "file"
    = file_field_tag "upload[file]"
    = submit_tag 'Analyze!'

Thanks to Rob Biedenharn for answering this five years ago on ruby-forum! http://www.ruby-forum.com/topic/125637

like image 85
will_d Avatar answered Oct 31 '22 08:10

will_d