Reputation: 2977
I'd like to make a simple file uploader using tag_form on Rails 3.2.8.
But when I try to submit a image file, I get an error saying
Error Message (when I try to submit a image file)
NoMethodError in CoursesController#attachment
undefined method `original_filename' for "2012-03-02 21.53.55.jpg":String
----- BEGIN P.S.(20121216 19:32) -----
or
Error Message (when I added ":multipart => true" on show.html.erb)
Encoding::UndefinedConversionError in CoursesController#attachment
"\xFF" from ASCII-8BIT to UTF-8
----- END P.S. -----
It seems that the program consider the file as String?
There might be some problem in the view file.
I'd appreciate it if you help me with this problem. Here's my codes.
app/view/show.html.erb
<%= form_tag(attachment_course_path, :action=>'attachment') do %>
<div class="field">
<%= label_tag :file %>
<%= file_field_tag :file %>
</div>
<div class="actions">
<%= submit_tag 'Submit' %>
</div>
<% end %>
app/controller/courses_controller.rb
def attachment
t = Time.now.strftime("%Y%m%d%H%M%S")
uploaded_io = params[:file]
File.open(Rails.root.join('public', 'upload', uploaded_io.original_filename), 'w') do |file|
file.write(uploaded_io.read)
end
end
config/routes.rb
resources :courses, :only => [ :show ] do
member do
post :attachment
end
end
Upvotes: 2
Views: 5571
Reputation: 12003
The problem seems similar to RoR upload Undefined encoding conversion
After setting :multipart => true
in form_tag
you need to open the file in binary mode ('wb'
instead of 'w
'):
app/controller/courses_controller.rb
...
File.open(Rails.root.join('public', 'upload', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
...
Upvotes: 1
Reputation: 7288
seems the form is not sending files with request. you need to set :multipart => true in form_tag.
Upvotes: 3