开发者

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. He开发者_如何学Cre 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'


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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜