Ruby on Rails upload file problem odd utf8 convers

2020-02-09 04:23发布

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'

3条回答
混吃等死
2楼-- · 2020-02-09 04:53

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

查看更多
姐就是有狂的资本
3楼-- · 2020-02-09 04:54
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
查看更多
狗以群分
4楼-- · 2020-02-09 04:55

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
查看更多
登录 后发表回答