【问题标题】:Error, Ruby on Rails: Encoding::UndefinedConversionError in CoursesController#attachment "\xFF" from ASCII-8BIT to UTF-8错误,Ruby on Rails:CoursesController#attachment "\xFF" 中的 Encoding::UndefinedConversionError 从 ASCII-8BIT 到 UTF-8
【发布时间】:2012-12-17 07:12:57
【问题描述】:

我想在 Rails 3.2.8 上使用 tag_form 制作一个简单的文件上传器。
但是当我尝试提交图像文件时,我收到一条错误消息

错误消息(当我尝试提交图像文件时)

CoursesController#attachment 中的编码::UndefinedConversionError
"\xFF" 从 ASCII-8BIT 到 UTF-8

如果您能帮我解决这个问题,我将不胜感激。
这是我的代码。


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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:

    尝试以二进制模式打开文件('wb' 而不是'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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-18
      • 2014-06-12
      • 2015-08-10
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2014-08-26
      相关资源
      最近更新 更多