gpt4 book ai didi

ruby-on-rails - 回形针 + RSpec : content_type validation

转载 作者:行者123 更新时间:2023-12-02 17:40:23 32 4
gpt4 key购买 nike

我在我的 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 中是否还有其他可用的验证来实现此目的?还是在这种情况下我应该选择自定义验证器?

最佳答案

Paperclip 于 2014 年 2 月 21 日 发布的最新版本 4.1.1 中解决了此问题。

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

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.txt文件为wrong.png并上传。

在 Paperclip 的先前版本中,wrong.png 以出色的表现通过了 content_type 验证,没有给出任何错误,因为 Paperclip 仅用于 检查上传文件的扩展名,而不是其中的内容。

然而,在 Paperclip 4.1.1 的当前版本中,相同的欺骗 wrong.png 未通过验证并在 View 中抛出以下错误:

Image has an extension that does not match its contents

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

Command :: file -b --mime-type '/var/folders/tg/8sxl1vss4fb0sqtcrv3lzcfm0000gn/T/a7f21d0002b0d9d91eb158d702cd930320140317-531-swkmb8' [paperclip] Content Type Spoof: Filename wrong.png (["image/png"]), content type discovered from file command: text/plain. See documentation to allow this combination.

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

希望我的发现能帮助其他人了解 Paperclip 的内容类型 验证如何随着时间的推移而得到改进。

关于ruby-on-rails - 回形针 + RSpec : content_type validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21610920/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com