2

我正在使用以下代码将图像上传到我的根 rails 目录的 /public/uploads/ 文件夹中。

 uploaded_io = params[:product_image]
 File.open(Rails.root.join('public','uploads', uploaded_io.original_filename), 'w') do |file|
    file.write(uploaded_io.read)
 end

我的表格看起来像这样

<%= form_tag({:action => :configure_product}, :multipart => true) do %>
<%= label_tag(:product_image, "Image:") %><br />
<%= file_field_tag 'product_image' %>
<%= submit_tag "Save and add another", :name => 'save and add another' %>
<%= submit_tag "Save", :name => 'save' %> 
<% end %>

但是在尝试提交表单时出现以下错误。

ConfigureCategoryController#configure_product 中的编码::UndefinedConversionError

"\xFF" 从 ASCII-8BIT 到 UTF-8

我将写作模式从“w”替换为“wb”,现在我得到了

ConfigureCategoryController#configure_product 中的 NoMethodError

nil:NilClass 的未定义方法“名称”

新的轨道。肯定会感谢您的帮助。

4

1 回答 1

6

您需要通过将 b 附加到 open 类型来将文件作为二进制文件打开。

File.open("#{ Rails.root }/tmp/uploaded_image.gif", "wb") do |f|

您遇到的另一个问题特定于您的应用程序所做的任何事情。

于 2013-03-13T14:33:56.987 回答