【问题标题】:Carrierwave different size limits for different file typesCarrierwave 针对不同文件类型的不同大小限制
【发布时间】:2015-06-29 06:45:57
【问题描述】:

我有一个允许的文件扩展名列表

def extension_white_list
  %w(pdf doc docx xls xlsx html tif gif jpg jpeg png bmp rtf txt)
end

以及模型中定义的尺寸限制验证

mount_uploader :inv_file, InvFileUploader

validates_size_of :inv_file, maximum: 25.megabyte, message: "Attachment size exceeds the allowable limit (25 MB)."

它工作正常,并且大小限制验证适用于所有定义的文件扩展名。

但我想对不同的文件应用不同的大小限制,即

  • (png 和 jpeg)限制为 5MB
  • PDF 限制为 20MB
  • 所有其他文件扩展名限制为 25MB

我怎样才能做到这一点?

【问题讨论】:

    标签: ruby-on-rails carrierwave


    【解决方案1】:

    你可以试试这个方法

    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
    

    【讨论】:

    • 您没有在 else 中检查该文件是否已结束 25MB。如果扩展名与 ["png", "jpg", "jpeg"]"pdf" 不匹配,您总是会抛出 You cannot upload a file greater than 25MB 错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多