0

我想使用 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?

4

1 回答 1

1

我认为你的validates_attachment_content_type定义是错误的。您不应将散列传递给:content_type选项,而应传递单个内容类型或类型数组

在您的情况下,应该执行以下操作:

validates_attachment_content_type :fax_document, 
       content_type: ["application/pdf", "application/octet-stream"] 
于 2016-05-09T18:50:37.577 回答