Buddy Lindsey
Buddy Lindsey

Reputation: 3630

Ruby on Rails upload file problem odd utf8 conversion error

I am trying to upload a file and i am getting the following error:

"\xFF" from ASCII-8BIT to UTF-8

I am pretty much following the rails guides in what they are doing. Here is the code I am using.

file = params[:uploaded_file]

File.open(Rails.root.join('public', 'images', file.original_filename), 'w') do |f|
  f.write(file.read)
end

I don't get why it doesn't work. What am I doing wrong?

Update -- Here is the application Trace

app/controllers/shows_controller.rb:16:in `write'
app/controllers/shows_controller.rb:16:in `block in create'
app/controllers/shows_controller.rb:15:in `open'
app/controllers/shows_controller.rb:15:in `create'

Upvotes: 11

Views: 8576

Answers (3)

Oleg Kovalenko
Oleg Kovalenko

Reputation: 101

dst_path = Rails.root.join('public', 'images', file.original_filename)
src_path = params[:uploaded_file].path
IO.copy_stream(src_path, dst_path) # http://ruby-doc.org/core-1.9.2/IO.html#method-c-copy_stream

Upvotes: 0

gorn
gorn

Reputation: 5340

I had similar issue with uploading binary files and your solution strangely did not work, but this one had, so here is it for anyone else having the same problem

file.tempfile.binmode

put this line before File.open. I think the reason is that the temporary file is opened in nonbinary mode after upload automatically, and this line switches it to binary, so rails does not try any automatic conversion (which is nonsense in case of binary file).

Upvotes: 1

esfourteen
esfourteen

Reputation: 501

I believe this is a change in how rails 3 works with ruby 1.9, since 1.9 supports encodings it will attempt to convert all strings to whatever encoding you have set in your app configuration (application.rb), typically this is 'utf-8'.

To avoid the encoding issue open the file in binary mode, so your mode would be 'wb' for binary writeable:

File.open(Rails.root.join('public', 'images', file.original_filename), 'wb') do |f|
  f.write(file.read)
end

Upvotes: 34

Related Questions