gpt4 book ai didi

ruby-on-rails - Carrierwave 对不同文件类型的不同大小限制

转载 作者:行者123 更新时间:2023-12-04 05:57:39 27 4
gpt4 key购买 nike

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

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

我怎样才能做到这一点?

最佳答案

你可以这样试试

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

关于ruby-on-rails - Carrierwave 对不同文件类型的不同大小限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31109352/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com