Carrier size limits for different file types
I have a list of allowed file extensions
def extension_white_list
%w(pdf doc docx xls xlsx html tif gif jpg jpeg png bmp rtf txt)
end
and validation of the size defined in the model
mount_uploader :inv_file, InvFileUploader
validates_size_of :inv_file, maximum: 25.megabyte, message: "Attachment size exceeds the allowable limit (25 MB)."
It works great and the size limit check is applied for all specific file extensions.
But I want to apply different size limits for different ie files
- 5MB limit for (png and jpeg)
- 20MB PDF limit
- 25MB limit for all other file extensions
How can I achieve this?
+3
source to share
1 answer
you can try this way
class Product < ActiveRecord::Base
mount_uploader :inv_file, InvFileUploader
validate :file_size
def file_size
extn = file.file.extension.downcase
size = file.file.size.to_f
if ["png", "jpg", "jpeg"].include?(extn) && size > 5.megabytes.to_f
errors.add(:file, "You cannot upload an image file greater than 5MB")
elsif (extn == "pdf") && size > 20.megabytes.to_f
errors.add(:file, "You cannot upload an pdf file greater than 20MB")
else
errors.add(:file, "You cannot upload a file greater than 25MB")
end
end
end
+3
source to share