Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a file extension only if there is a file extension? Re: carrierwave

I am using CarrierWave, and I would like to validate file names and only allow file uploads if the extension is .gif, .png, .jpg, .jpeg, or if there is no file extension.

Sometimes users upload files with no extensions. For example:

http://t2.gstatic.com/images?q=tbn:ANd9GcTCD2TLvYI8a4ChgBaYK_JaRfedvXLr3HXQfj0arXXAii3o2yjf

I am aware of the possibility of uncommenting the following lines in uploaders/image_uploader.rb, but I don't know of a way of additionally saying "allow any of these extensions only if there is a file extension".

# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
#def extension_white_list
#  %w(gif jpg jpeg png)
#end

As well, in my model I have a validation as follows, but for some reason bad-extension.bad passes.

validates :image, allow_blank: true, format: {
    with: %r{\.(gif|jpe?g|png)\z}i,
    message: 'must be a GIF, JPG, or PNG'
}, if: :filename_has_extension?

def filename_has_extension?
  image =~ /\./
end
like image 562
user664833 Avatar asked Aug 29 '12 18:08

user664833


1 Answers

Well Why not use Mimetype comparison of the file in validation process there is ruby gem call mimetype that can help you in your quest

something like this

AVAILABLE_MIMETYPE = %w(image/gif)

validate :mime_type_of ,:if => :if_changed?


private
def mime_type_of
  AVAILABLE::MIMETYPE.include?(MIME::Types.type_for[image_path][0]) 
end

def if_changed?
  new_record? or image_changed?
end

Even CarrierWave Include MimeType Gem Internally check if that can help too

Hope this Help

like image 162
Viren Avatar answered Sep 21 '22 23:09

Viren