簡體   English   中英

使用Rails上傳文件時出錯

[英]Error uploading a file with rails

我想上傳帶有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 %>

另外,使用其他方法上傳文件會更容易...對此有什么好辦法嗎? 謝謝

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

代替

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

b模式以二進制模式打開文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM