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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With