开发者

Is there a way to blacklist extensions in Paperclip?

I have an app that must accept almost every file type except those known to be malitious (ie exe, dll, bat, etc). I am using Paperclip and am wondering if there is a way to do this. Following the commit on github, https://github.com/thoughtbot/paperclip/commit/020625921adae884534608d76c11f65692e4bbec, it looks like it may be possible. But I am unsure.

UPDATE: I could not find a Paperclip way of doing things, however I did add this custom validation:

  def extension_not_blacklisted?
 #An attempt to make a black开发者_JAVA技巧list 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


Your custom validation method is probably the only way. At least for now, Paperclip can validate only content types, with something like:

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

and it validates inclusion, not exclusion.


You can use a regular expression that uses negative lookahead:

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


Use a before_post_process filter and return false if the extension is in your blacklist - returning false will prevent the rest of the processing chain from executing.

See the bottom of this page for an example on checking for a valid file size.

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


Create a custom validation.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜