user727403
user727403

Reputation: 1977

Error uploading a file with rails

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

Upvotes: 3

Views: 1498

Answers (1)

Damien
Damien

Reputation: 27463

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.

Upvotes: 7

Related Questions