Rails4 - encoding issue when writing/saving images
In my app an user can upload an image that will be stored.
Following Ruby tutorial I do in this manner:
def self.add_image(image, odl)
odl_id = odl.id
# create the dir where the file will stored
FileUtils.mkdir_p("#{Rails.root}/public/odl/#{odl_id}/images/")
File.open("#{Rails.root}/public/odl/#{odl_id}/images/#{image.original_filename}",
'w') do |file|
file.write(image.read)
end
if
File.exists?("#{Rails.root}/public/odl/#{odl_id}/images/#{image.original_filename}")
return true
else
return false
end
rescue Exception => e
puts "Exception msg: #{e.message}"
return false
end
I can't save it, because it raise this exception:
Exception msg: "\xD6" from ASCII-8BIT to UTF-8
Then I try to force UTF-8 encoding in this manner:
File.open("#{Rails.root}/public/odl/#{odl_id}/images/#{image.original_filename}",
'w:UTF-8') do |file|
file.write(image.read.force_encoding("UTF-8"))
end
That solve for a moment the problem, but the images are not showed in the
browser (it appears the "image broken" but no error - no 404), if I open
directly the image (or the url of the image) it shows correctly.
Any suggestion?
No comments:
Post a Comment