Question

I'm trying to get an ajax upload working with rails 3.1.3 and paperclip.

I found this solution to my problem Rails 3 get raw post data and write it to tmp file, but using this, I get an 'encoding undefined conversion error "\xFF" from ASCII-8BIT to UTF-8.

The error occurs at the line @user.photo = @user.photo = QqFile.parse(params[:qqfile], request)

I have not edited the code supplied in the previous answer, but I'll include it here so you don't have to switch back and forth.

the gem list paperclip, returns 2.5.2, 2.4.5, 2.3.8

my controller

 def create


    @user = User.new(params[:user])

    @user.photo = QqFile.parse(params[:qqfile], request)
    if @user.save
        return render :json => @user
    else
        return render :json => @user.errors
    end
  end

qq_file.rb

# encoding: utf-8
require 'digest/sha1'
require 'mime/types'

# Usage (paperclip example)
# @asset.data = QqFile.new(params[:qqfile], request)
class QqFile < ::Tempfile

  def initialize(filename, request, tmpdir = Dir::tmpdir)
    @original_filename  = filename
    @request = request

    super Digest::SHA1.hexdigest(filename), tmpdir
    fetch
  end

  def self.parse(*args)
    return args.first unless args.first.is_a?(String)
    new(*args)
  end

  def fetch
    self.write @request.raw_post
    self.rewind
    self
  end

  def original_filename
    @original_filename
  end

  def content_type
    types = MIME::Types.type_for(@request.content_type)
      types.empty? ? @request.content_type : types.first.to_s
  end
end
Was it helpful?

Solution

This was an encoding error related to Ruby 1.9.2 (or I believe Ruby 1.9+). this github post lead to the answer https://github.com/lassebunk/webcam_app/issues/1

You must specify raw_post.force_encoding("UTF-8") when reading an upload as far as I could tell (I'm not a great programmer).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top