我想使用 Paperclip gem (4.3.6) 从第 3 方 API 流式传输文件,并将 HTTP 响应的主体用作代表传真的 ActiveRecord 模型上的附件。
class Fax
has_attached_file :fax_document
validates_attachment_content_type :fax_document, content_type: { content_type: ["application/pdf", "application/octet-stream"] }
end
我正在使用下面的代码从 API 服务器获取 HTTP 响应并将其保存为传真模型上的附件。(为简洁起见,以下代码稍作修改)。
#get the HTTP response body
response = download(url)
#add the necessary attributes to the StringIO class. This technique is demonstrated in multiple SO posts.
file = StringIO.new(response)
file.class.class_eval { attr_accessor :original_filename, :content_type }
file.original_filename = "fax.pdf"
file.content_type = 'application/pdf'
#save the attachment
fax = Fax.new
fax.fax_document = file
fax.save
该response
变量包含看起来像 pdf 二进制对象的字符串表示形式,并fax.save
引发 content_type not valid 错误。如果我明确放宽传真模型上的回形针验证,使用do_not_validate_attachment_file_type :fax_document
,则附件将正确保存。
我怀疑 Paperclip 内容类型验证失败,因为它无法判断返回的内容实际上是“应用程序/pdf”。
为什么 Paperclip 会引发 content_type 无效错误?我如何告诉 Paperclip 响应的正文是 pdf?