使用rails上传文件时出错

时间:2011-11-24 18:46:35

标签: ruby-on-rails ruby upload

我想用rails上传一个真正的字体,但我收到了这个错误:

Encoding::UndefinedConversionError in FontsController#create
"\xE6" from ASCII-8BIT to UTF-8

以下是控制器中的代码:

  def create
    @font = Font.new(params[:font])
    upload = params[:upload]
    name =  upload['datafile'].original_filename
    @font.font_type = File.extname(name)
    @font.location = './public/fonts/' + name

    puts "\n\n---------------------------\n#{upload['datafile'].class}\n-----------------------------\n\n"

    File.open(@font.location, "w+") { |f| f.write(upload['datafile'].read) }

    #Save the license
    @font.save

    respond_to do |format|
      if @font.save
        format.html { redirect_to(@font, :notice => 'Font was successfully created.') }
        format.xml  { render :xml => @font, :status => :created, :location => @font }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @font.errors, :status => :unprocessable_entity }
      end
    end
  end

并在视图中:

<%form_tag({:controller => 'fonts', :action=> 'create'}, {:multipart => true}) do%>
  <% if @font.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@font.errors.count, "error") %> prohibited this font from being saved:</h2>

      <ul>
      <% @font.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<%= file_field :upload, :datafile %>

  <div class="actions">
            <%= submit_tag "Upload License" %>
  </div>
<% end %>

另外,使用其他方法进行文件上传会更容易吗?这有什么好的宝石吗?谢谢

1 个答案:

答案 0 :(得分:7)

File.open(@font.location, "wb") { |f| f.write(upload['datafile'].read) }

而不是

File.open(@font.location, "w+") { |f| f.write(upload['datafile'].read) }

b模式以二进制模式打开文件。