Reputation: 2876
I'm trying to get the original_filename and other stuff from an uploaded file.
The code in the view looks like:
<%= form_for(@datafile, url: user_data_files_path) do |f| %>
<%= f.file_field :data%>
<%= f.submit "Upload file", class: "btn btn-large btn-primary" %>
<% end %>
the params value in the debug console are:
{"utf8"=>"✓",
"authenticity_token"=>"Z4suAyN3zOpz1qBKllaDs3L4flz6Rm6HnN0CIdJvmcE=",
"data_file"=>{"data"=>#<ActionDispatch::Http::UploadedFile:0x007ff46b74e390 @tempfile=#<Tempfile:/var/folders/gf/lft827zj55b5wdj3208vpsy40000gn/T/RackMultipart20130803-635-q6wtb6>,
@original_filename="application.html.erb",
@content_type="application/octet-stream",
@headers="Content-Disposition: form-data; name=\"data_file[data]\"; filename=\"application.html.erb\"\r\nContent-Type: application/octet-stream\r\n">},
"commit"=>"Upload file",
"user_id"=>"1"}
I'm trying to retrieve things like original_filename and data, in my controller I have:
def create
@datafile = DataFile.new
uploaded_io = params[:data_file]
flash[:error]= '' + uploaded_io[:@original_filename]
redirect_to new_user_data_file_url
end
but I get an error: no implicit conversion of nil into String
in the flash[:error]
line.
I have tried to acces via:
uploaded_io[:original_filename]
that gives me the same error, or
uploaded_io.original_filename
and I get NoMethodError
The weird thing I see is that flash[:error]= '' + uploaded_io.to_s
gives me the data_file hash, so.. I don`t understand what is happening.
Can someone help me to solve this issue?
Upvotes: 1
Views: 1375
Reputation: 2876
I've found that the error was in thinking that params[:data_file]
contained the file. The file is in params[:data_file][:data]
(look at the view's form) and then that file has the method (variable instance) original_filename. So doing params[:data_file][:data].original_filename
returns the file's name.
Upvotes: 3