【问题标题】:Paperclip validation of StringIO not validStringIO 的回形针验证无效
【发布时间】:2016-09-04 04:50:47
【问题描述】:

我想使用 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 无效错误。如果我使用do_not_validate_attachment_file_type :fax_document 明确放宽传真模型上的回形针验证,则附件将正确保存。

我怀疑 Paperclip 内容类型验证失败,因为它无法判断返回的内容实际上是“应用程序/pdf”。

为什么 Paperclip 会引发 content_type not valid 错误?我如何告诉 Paperclip 响应的正文是 pdf?

【问题讨论】:

    标签: ruby-on-rails paperclip paperclip-validation


    【解决方案1】:

    我认为您的validates_attachment_content_type 定义是错误的。您不应将哈希传递给 :content_type 选项,而是传递 single content type or an array of types

    在你的情况下,应该这样做:

    validates_attachment_content_type :fax_document, 
           content_type: ["application/pdf", "application/octet-stream"] 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 2015-10-10
      相关资源
      最近更新 更多