【问题标题】:Ruby: Is there a way to specify your encoding in File.write?Ruby:有没有办法在 File.write 中指定你的编码?
【发布时间】:2021-11-09 20:21:33
【问题描述】:

TL;DR

如何在 File.write 上指定编码模式,或者如何以类似的方式将图像二进制文件保存到文件中?

更多详情

我正在尝试从 Trello 卡下载图像,然后将该图像上传到 S3,以便它具有可访问的 URL。我已经能够从 Trello 以二进制文件的形式下载图像(我相信它是某种形式的二进制文件),但是我在使用 File.write 将其保存为 .jpeg 时遇到了问题。每次我尝试这样做时,都会在我的 Rails 控制台中出现这个错误:

Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8
from /app/app/services/customer_order_status_notifier/card.rb:181:in `write'

下面是触发它的代码:

def trello_pics
    @trello_pics ||=
    card.attachments.last(config_pics_number)&.map(&:url).map do |url|
      binary = Faraday.get(url, nil, {'Authorization' => "OAuth oauth_consumer_key=\"#{ENV['TRELLO_PUBLIC_KEY']}\", oauth_token=\"#{ENV['TRELLO_TOKEN']}\""}).body
      File.write(FILE_LOCATION, binary) # doesn't work
      run_me
    end
  end

所以我认为这一定是 File.write 将输入转换为文件的方式存在问题。有没有办法指定编码?

【问题讨论】:

标签: ruby-on-rails ruby image file trello


【解决方案1】:

AFIK 你不能在执行write 的时候做,但是你可以在创建File 对象的时候做;这里是一个 UTF8 编码的例子:

File.open(FILE_LOCATION, "w:UTF-8") do 
  |f|
  f.write(....)
end

另一种可能性是使用external_encoding 选项:

File.open(FILE_LOCATION, "w", external_encoding: Encoding::UTF_8)

当然,这假设写入的数据是String。如果您有(打包的)二进制数据,您将使用"wb" 打开文件,并使用syswrite 而不是write 将数据写入文件。

更新 正如engineersmnky 在评论中指出的那样,编码的参数也可以作为参数传递给write 方法本身,例如

IO::write(FILE_LOCATION, data_to_write, external_encoding: Encoding::UTF_8)

【讨论】:

  • IO::write 也接受一个编码参数。
猜你喜欢
  • 1970-01-01
  • 2023-01-19
  • 2015-05-26
  • 1970-01-01
  • 2023-04-02
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多