【问题标题】:CarrierWave validate content type before processing a fileCarrierWave 在处理文件之前验证内容类型
【发布时间】: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

标签: ruby-on-rails carrierwave


【解决方案1】:

我正在回答这个两年前的问题。 CarrierWave 内容类型白名单仅依赖于文件扩展名。我尝试将 SWF 文件的扩展名更改为 JPG 并直接在 UI 上得到一个冗长的错误:

验证失败:使用 MiniMagick 操作照片失败,可能不是图像?原始错误:'转换 /home/../projects/rails/../tmp/1588146379-380224569365897-0005-2916/android-916817f.png -auto-orient -resize 170x200^ -sharpen 0x1 -gravity Center -background rgba(255,255,255,0.0) -extent 170x200 /tmp/image_processing20200429-20696-ek1vs1.png` 失败并出现错误:

整晚都在寻找解决方案,但在这个话题上得到的太少了。 This answerthis wiki 帮助了我。

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :file

  before :process, :validate

  process resize_to_fill: [170, 200], convert: :jpg
  .
  .
  def validate(file)
    begin
      image = MiniMagick::Image.open(file.path)
    rescue
      raise "Image format isn't valid"
    end
  end
end

【讨论】:

    【解决方案2】:

    请确保您的机器上有 Imagemagick installed

    在上传器中我已经包含了

      def content_type_blacklist
        %w(image/jpeg image/png image/gif)
      end
    

    根据内容类型过滤图像文件。对于图像文件,您必须具有不同的内容类型。

    【讨论】:

    • 这是通过扩展过滤掉的,而不是内容类型,我在帖子中专门写过。
    • @jedi 哦,对不起,我刚刚看到你的问题,我现在已经更新了答案
    • 是的,但是内容类型很多,因此将整个庞大的内容类型列表包含在黑名单中以仅涉及图像是没有意义的,对吧? content_type_whitelist 应该按照他们的文档工作,但事实并非如此。
    • 你只处理图像文件吗?或者excel和words文件,如果你只有图像文件我相信不会有很多你不能列出的内容类型......
    • 是的,我只想将这些内容类型列入白名单:image/jpeg image/png image/gif
    猜你喜欢
    • 2012-10-05
    • 2012-07-31
    • 2011-03-16
    • 2014-08-15
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多