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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With