【问题标题】:Is there a way to blacklist extensions in Paperclip?有没有办法将 Paperclip 中的扩展列入黑名单?
【发布时间】:2011-07-26 19:07:59
【问题描述】:

我有一个应用程序必须几乎接受所有文件类型,除了那些已知的恶意文件(即 exe、dll、bat 等)。我正在使用回形针,想知道是否有办法做到这一点。在 github 上提交 https://github.com/thoughtbot/paperclip/commit/020625921adae884534608d76c11f65692e4bbec 之后,看起来有可能。但我不确定。

更新:我找不到回形针的处理方式,但我确实添加了这个自定义验证:

  def extension_not_blacklisted?
 #An attempt to make a blacklist command when saving...
 forbiden_types = Array.new()
 forbiden_types << "jpg" << "exe" <<"dll" 
 path_array = attachment.to_s.split(".")
 extension = path_array.pop
 extension_with_extras = extension.to_s.split("?")
 extension = extension_with_extras[0]

forbiden_types.each do |f|
  if f == extension
  errors.add(:attachment,'FORBIDEN FILE EXTENSION: ' + extension)
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 paperclip attachment


    【解决方案1】:

    您的自定义验证方法可能是唯一的方法。至少目前,Paperclip 只能验证内容类型,例如:

    validates_attachment_content_type :attachment, :content_type => ['image/png', 'application/pdf'], :message => 'should be a valid type'
    

    它验证包含,而不是排除。

    【讨论】:

      【解决方案2】:

      您可以使用使用负前瞻的正则表达式:

      validates_attachment_content_type :attachment, :content_type => /\/(?!(php|pl|exe|pm|cfm|asp)$)/
      

      【讨论】:

        【解决方案3】:

        使用 before_post_process 过滤器并返回 false 如果扩展在您的黑名单中 - 返回 false 将阻止处理链的其余部分执行。

        有关检查有效文件大小的示例,请参见本页底部。

        https://github.com/thoughtbot/paperclip/wiki/Thumbnail-Generation

        【讨论】:

        • before_post_process 似乎只适用于为图像制作缩略图,因为我返回 false 并且它仍然上传大图像,但不会生成缩略图。
        【解决方案4】:

        创建自定义验证。

        BANNED_FILE_EXTENSIONS = [
          ".exe",
          ".js",
          ".sh",
          ".shar"
        ].freeze
        
        
        validate :file_extension_is_allowed
        
        
        def file_extension_is_allowed
          errors.add( :attachment, "is not an allowed file extension" ) if BANNED_FILE_EXTENSIONS.include?( File.extname( self.attachment_file_name ) )
        end
        

        【讨论】:

          猜你喜欢
          • 2012-04-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-07
          • 1970-01-01
          • 2019-05-20
          • 2021-08-25
          相关资源
          最近更新 更多