ruby-on-rails 使用Shrine保存PDF

qncylg1j  于 2023-04-08  发布在  Ruby
关注(0)|答案(1)|浏览(175)

我正在尝试使用Shrine保存pdf文件。在Shrine readme之后,我正在归因于
my_model.image = File.open('my_pdf.pdf')
但这会引发一个错误:

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

我该怎么做呢?有办法用Shrine保存二进制文件吗?
以下是我使用的上传器:

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
wsewodh2

wsewodh21#

你可以使用类似try_encoding的东西从ASCII-8BIT或其他转换:

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

相关问题