3

I'm trying to save pdf files with Shrine. Following Shrine readme, I'm attributing

my_model.image = File.open('my_pdf.pdf')

but that raises an error:

Encoding::UndefinedConversionError: "\xFE" from ASCII-8BIT to UTF-8

How can I acomplish this? There is a way to save binary files with Shrine?

Here is the uploader I'm using:

class DocumentUploader < Shrine
  plugin :logging
  plugin :validation_helpers
  plugin :determine_mime_type, analyzer: :mimemagic
  plugin :data_uri

  Attacher.validate do
    validate_max_size 20*1024*1024, message: "is too large (max is 20 MB)"
    validate_mime_type_inclusion %w[
      image/jpeg
      image/gif
      image/bmp
      image/png
      image/tiff
      application/pdf
    ]
  end
end
rwehresmann
  • 1,108
  • 2
  • 11
  • 27
  • 1
    You need to open binary files in binary mode: `my_model.image = File.open('my_pdf.pdf', 'rb')` – Janko Apr 12 '18 at 10:53
  • also make sure your my_model.image can receive binary, if it's a database table and field that would be a blob – peter Apr 12 '18 at 12:36

1 Answers1

0

you can use something like try_encoding to convert from ASCII-8BIT or others:

def try_encoding(new_value)
  if new_value.is_a? String
    begin
      # Try it as UTF-8 directly
      cleaned = new_value.dup.force_encoding('UTF-8')
      unless cleaned.valid_encoding?
        # Some of it might be old Windows code page
        cleaned = new_value.encode('UTF-8', 'Windows-1252')
      end

      new_value = cleaned
    rescue EncodingError
      # Force it to UTF-8, throwing out invalid bits
      new_value.encode!('UTF-8', invalid: :replace, undef: :replace)
    end

    new_value
  end
end
KhogaEslam
  • 2,528
  • 1
  • 20
  • 21