2

我正在开发一个 Rails 应用程序,它允许用户通过神社将他们的图像上传到 AWS S3。到目前为止的设置工作得很好——但是,我想知道是否有任何直接的方法可以提取每个用户的上传总大小。

例如,我确实希望免费用户只允许上传最大 500MB,而会员只能上传 4GB。

在 Github 或 Google 上没有发现任何可用的东西,一般来说,也许有人可以分享他们的知识。干杯!

当前代码:

照片.rb

class Photo < ApplicationRecord
  include ImageUploader[:image]

  before_create :set_name

  belongs_to :employee
  belongs_to :user

  private

    def set_name
      self.name = "Photo"
    end
end

image_uploader.rb

require "image_processing/mini_magick"

class ImageUploader < Shrine
  include ImageProcessing::MiniMagick
  plugin :determine_mime_type
  plugin :remove_attachment
  plugin :store_dimensions
  plugin :validation_helpers
  plugin :pretty_location
  plugin :processing
  plugin :versions

  Attacher.validate do
    validate_max_size 5.megabytes, message: "is too large (max is 5 MB)"
    validate_mime_type_inclusion %w[image/jpeg image/png], message: " extension is invalid. Please upload JPEGs, JPGs and PNGs only."
    validate_min_width 400, message: " must have a minimum width of 400 pixel."
    validate_min_height 250, message: " must have a minimum height of 250 pixel."
  end

  process(:store) do |io, context|

    size_800 = resize_to_limit!(io.download, 800, 800)
    size_300 = resize_to_limit!(io.download, 300, 300)

    {original: io, large: size_800, small: size_300}
  end
end
4

2 回答 2

3

如果您想image在照片模型的列上添加验证错误消息,请在 Shrine 验证中执行此操作,因为您可以在那里访问照片记录。

class ImageUploader < Shrine
  # ...

  Attacher.validate do
    record #=> #<Photo ...>

    all_images = record.user.photos
      .select { |photo| photo.image_attacher.stored? }
      .map { |photo| photo.image[:large] }

    total_size = all_images.map(&:size).inject(0, :+)

    if total_size + get.size > 500.megabytes
      errors << "exceeds total maximum filesize for your account (max is 500MB)"
    end

    # ...
  end
end

首先,我们只过滤存在并上传到永久存储的附件(例如,如果您使用后台,则将有一段时间只附加缓存文件)。

然后我们总结所有large版本的图像大小,如您的示例所示。

最后,我们将当前附件大小添加到总大小中,如果超出限制,我们将添加验证错误。

于 2017-01-07T00:59:02.380 回答
0

So this is my solution - a custom validator. Very basic, but I think this shall do (not fully tested, need to catch a flight):

class Photo < ApplicationRecord
  include ImageUploader[:image]
  include ActiveModel::Validations

  before_create :set_name

  belongs_to :employee
  belongs_to :user

  validate :upload_size_validation

  private

    def set_name
      self.name = "Photo"
    end

    def upload_size_validation
      size = 0

      user.photos.each do |photo|
        byebug
        size = size + photo.image[:large].size.to_i
      end

      errors[:photo] << " cannot be uploaded as you hit the quota of 5 MB" if size > 50000
    end
end

If there is a better solution, please share !

于 2017-01-06T15:06:07.583 回答