【发布时间】: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 将输入转换为文件的方式存在问题。有没有办法指定编码?
【问题讨论】:
-
这能回答你的问题吗? Write and read a file with utf-8 encoding
-
IO#binwrite来自文档:“与 ::write 相同,但以二进制模式和 ASCII-8BIT 编码打开文件” -
或
File.open(FILE_LOCATION, 'wb') do |file|; file.write(data); end。 ruby-doc.org/core-2.5.0/IO.html#method-c-new -
@Int'lManOfCodingMystery 我不这么认为,但我可能是错的
-
@engineersmnky 如果您打开一个文件实例,您可以在流式传输响应时写入。否则,请使用较短的变体。 lostisland.github.io/faraday/usage/streaming
标签: ruby-on-rails ruby image file trello