Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error, Ruby on Rails: Encoding::UndefinedConversionError in CoursesController#attachment "\xFF" from ASCII-8BIT to UTF-8

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)

Encoding::UndefinedConversionError in CoursesController#attachment
"\xFF" from ASCII-8BIT to UTF-8

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', :multipart => true) 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
like image 303
wiz Avatar asked Dec 17 '12 07:12

wiz


1 Answers

Try to open the file in binary mode ('wb' instead of 'w'):

  ...
  File.open(Rails.root.join('public', 'upload', uploaded_io.original_filename), 'wb') do |file|
    file.write(uploaded_io.read)
  end

Ruby Docs IO Open Mode

like image 57
dimuch Avatar answered Oct 30 '22 06:10

dimuch