Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 891
Buddy Lindsey Avatar asked Feb 14 '11 04:02

Buddy Lindsey


2 Answers

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
like image 92
esfourteen Avatar answered Jan 19 '23 09:01

esfourteen


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).

like image 36
gorn Avatar answered Jan 19 '23 09:01

gorn