错误,Ruby on Rails的:编码:: UndefinedConversionError在Co

2019-07-05 12:45发布

我想用tag_form on Rails的3.2.8做一个简单的文件上传。
但是,当我尝试提交一个图像文件,我得到一个错误说

错误信息(当我尝试提交一个图像文件)

编码:: UndefinedConversionError在CoursesController#附件
“\ XFF” 从ASCII-8BIT为UTF-8

我会很感激,如果你帮我解决这个问题。
这里是我的代码。


应用程序/视图/ 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 %>


应用程序/控制器/ 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


配置/ routes.rb中

resources :courses, :only => [ :show ] do
  member do
    post :attachment
  end
end

Answer 1:

尽量以二进制方式打开文件( 'wb' ,而不是'w' ):

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

红宝石文件IO开放模式



文章来源: Error, Ruby on Rails: Encoding::UndefinedConversionError in CoursesController#attachment “\\xFF” from ASCII-8BIT to UTF-8