载波返回错误的文件大小

时间:2018-10-23 09:32:00

标签: ruby-on-rails ruby carrierwave

我有以下模型:

class Asset < ApplicationRecord
  ## Associations ##
  belongs_to :assetable, polymorphic: true, optional: true

  ## Validations ##
  validate { |a| a.blank_to_nil :description }
  validate :file_size

  ## Callbacks ##
  before_save :default_attrs

  ## Misc ##
  mount_base64_uploader :attachment, AttachmentUploader

  ## Methods ##
  def version_url(ver)
    return nil unless attachment.versions[:images].send(ver)
    attachment.versions[:images].send(ver).url
  end

  private

  def assetable_const
    assetable_type.constantize
  end

  def attachment_size
    attachment.size
  end

  def assetable_max_file_size
    return 0.0 unless assetable_type
    assetable_type.constantize.max_file_size
  end

  def default_attrs
    self.alt = default_file_name if alt.blank?
    self.title = default_file_name if title.blank?
  end

  def default_file_name
    "#{default_assetable_name}-#{default_assetable_stamp}"
  end

  def default_assetable_name
    "#{assetable_type.downcase}-#{assetable_id}"
  end

  def default_assetable_stamp
    "#{Time.now.strftime('%d%m%y')}-#{attachment.filename}"
  end

  # for now add to attachment and title
  # error doesnt show on CMS under attachment
  def file_size
    return if attachment_size.to_f <= assetable_max_file_size.megabyte.to_f
    errors.add(
      :attachment,
      I18n.t(
        'validations.assets.max_file_size',
        value: assetable_max_file_size.to_s
      )
    )
  end
end

我的问题来自验证文件大小的最后一种方法。每个模型中都有一个单独的方法,其中包含资产max_file_size:

class Content::Panels::ImageOnly < Content::Panel
  ## Includes ##
  include Assetable

  ## Associations ##
  belongs_to :panel_holder, polymorphic: true

  ## Validations ##
  validates_presence_of :asset

  ## Misc ##
  set_assetables :asset

  ## Methods ##
  def self.max_file_size
    1.0
  end

我正在上传我附加的图像-680 KB。当我在我的'file_size'方法中放入binding.pry时,我可以看到附件.size返回的值超过1MB:

pry(#<Asset>)> attachment.size.to_f
=> 2481189.0

此值是以字节为单位返回的吗?如果显示为位,则为实际文件大小的一半(可能由于压缩魔术而可能),但我认为它将返回字节。

除非增加最大文件大小,否则我的方法每次都会失败:

def max_file_size
  3.0
end

将其设置为3MB即可通过验证。 2MB失败。任何帮助将不胜感激

编辑:正在上传的图片: https://imgur.com/a/3TG9rLt

1 个答案:

答案 0 :(得分:0)

对于其他失去理智的人-使用各种不同的文件进行测试-文件大小似乎以位为单位返回。