【问题标题】:Error uploading a file with rails使用 rails 上传文件时出错
【发布时间】:2012-01-05 21:06:39
【问题描述】:

我想上传带有 rails 的 true type 字体,但收到此错误:

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 %>

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

【问题讨论】:

    标签: ruby-on-rails ruby upload


    【解决方案1】:

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

    而不是

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      相关资源
      最近更新 更多