【问题标题】:Paperclip + RSpec: content_type validationPaperclip + RSpec:content_type 验证
【发布时间】:2014-02-06 18:22:08
【问题描述】:

我在我的 Rails 应用程序中使用Paperclip 来附加images。 我在我的模型中声明了对 content_type 的验证为

 validates_attachment :image,
  :content_type => { :content_type => ["image/jpg", "image/gif", "image/png"] }

我有两个示例,一个具有有效图像,另一个具有无效图像
对于无效图像,我只是将 .txt 文件重命名为 .png

 it "Image is valid" do
    image = File.new("#{Rails.root}/spec/support/right.png")
    expect(FactoryGirl.build(:pin, image: image)).to be_valid
 end
 it "Image is invalid" do
   image = File.new("#{Rails.root}/spec/support/wrong.png")
   expect(FactoryGirl.build(:pin, image: image)).to have(1).errors_on(:image_content_type)
 end

我希望我的两个示例都能成功运行。但是,我的第二个例子失败了。 我没有收到 wrong.png 的 content_type 的任何错误。

我认为 Paperclip 的 content_type 验证实际上会检查上传文件的文件格式(二进制数据编码)。但似乎在这里,它只是检查文件扩展名。此验证是否仅检查上传文件的扩展名?

我可能在这里遗漏了一些东西(配置?)。 Paperclip 中是否有任何其他可用的验证来实现这一点?还是在这种情况下我应该选择自定义验证器?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec paperclip


    【解决方案1】:

    Paperclip 的最新版本4.1.1 已在February 21, 2014 发布。

    我的以下两个示例现在都正确通过了。

    it "Image is valid" do
        image = File.new("#{Rails.root}/spec/support/right.png")
        expect(FactoryGirl.build(:pin, image: image)).to be_valid
    end
    it "Image is invalid" do
       image = File.new("#{Rails.root}/spec/support/wrong.png")
       expect(FactoryGirl.build(:pin, image: image)).to have(1).errors_on(:image_content_type)
    end
    

    经过一番研究发现, 当我上传invalid image 时,

    例如:恶搞(重命名)wrong.txt 文件为wrong.png 并上传。

    在 Paperclip 的先前版本中,wrong.png 通过content_type 验证并没有给出任何错误,因为Paperclip 仅用于上传文件的check the extensions,而不是其中的内容。

    然而,在当前版本的 Paperclip 4.1.1 中,相同的欺骗 wrong.png 验证失败并在视图中抛出以下错误:

    Image has an extension that does not match its contents
    

    在调查服务器日志条目后,我发现以下内容:

    命令 :: file -b --mime-type '/var/folders/tg/8sxl1vss4fb0sqtcrv3lzcfm0000gn/T/a7f21d0002b0d9d91eb158d702cd930320140317-531-swkmb8' [回形针] Content Type Spoof: Filename wrong.png (["image/png"]), 从文件命令中发现的内容类型:文本/纯文本。看 允许这种组合的文档。

    在这里,您可以看到 Paperclip 实际上检查了上传文件的内容,指出text/plain,并且还错误地指出了Content Type Spoof

    希望我的发现能帮助其他人了解 Paperclip's content-type 验证随着时间的推移是如何改进的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多