3

I am wanting to upload a true type font with rails but am recieving this error:

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

Here is the code in the controller:

  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

and in the view:

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

also, would it be easier to use some other method for file uploading...are there any good gems for this? Thanks

1 Answer 1

7

Write

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

instead of

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

The b mode opens the file in binary mode.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.