【发布时间】:2018-04-08 18:50:28
【问题描述】:
我现在已经尝试了所有方法,但在对正在上传的文件执行实际处理之前,我似乎无法弄清楚如何在 CarrierWave 中添加内容类型验证。这样做的原因是我只想允许图像,但用户可以上传欺骗内容文件并将file.pdf 文件重命名为file.jpg。到目前为止我尝试过的步骤:
photo_uploader.rb
def content_type_whitelist
/image\//
end
我已经在我的上传器中尝试了validate_integrity,但也没有运气。
我也尝试过覆盖 CarrierWave 错误消息(在我看来这实际上对我来说很奇怪):
en:
errors:
messages:
content_type_whitelist: "You are not allowed to upload %{content_type} file"
但我收到 MiniMagic 的错误
"Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: %{e}"
问题是我想显示rails 验证,以便当内容类型不是我在模型中定义的类型之一时,它会显示类似"File should be one of image/jpeg, image/png, image/gif" 的消息。所以我需要一种方法来强制在图像处理之前触发 rails 验证,尽管我认为这不太可能。
Here 他们说应该包含CarrierWave::Uploader::MagicMimeWhitelist 以便执行mime 类型验证,所以我尝试过,但得到uninitialzied constant CarrierWave::Uploader::MagicMimeWhitelist(服务器之前重新启动)
include CarrierWave::Uploader::MagicMimeWhitelist
def whitelist_mime_type_pattern
/image\//
end
我尝试过使用carrier-mimetype-fu,但在包含CarrierWave::MimetypeFu 之后,我得到了unitilzied constant CarrierWave::MimetypeFu
你有这方面的经验吗?
【问题讨论】:
-
只是抛开一些随意的想法,在包含之前您是否需要该文件?通常,未初始化的常量错误发生在文件找不到或未包含在使用之前。
-
在 Rails 中,默认情况下它是自动需要的 :) 无论如何,我刚刚尝试了更深入的调试,这就是我发现的。 Carrierwave 可能根据文件扩展名更改内容类型。
file -I this_is_pdf.jpg => text/plainuploader = PhotoUploader.new.cache!("this_is_pdf.jpg")uploader.file.content_type => image/jpg