Maxence
Maxence

Reputation: 2339

Recovering file size of a specific paperclip image style

I need to know the file size of a paperclip attachment image style (not only the :original style which has a dedicated field already) and I am a bit struggling at the moment.

Upvotes: 1

Views: 485

Answers (1)

morgant
morgant

Reputation: 2225

I had the same need. As you mention Paperclip attachments have a database field for the :original style file size, but the size method just returns that value.

I wanted a quick solution that would allow determining of attachment size in either filesystem or S3 (I use both) and without having to actually perform HTTP header checks. Upon looking at the Paperclip::Storage structure, I realized I could override the size method for each storage method by putting the following in my config/initializers/paperclip.rb:

module Paperclip
  module Storage
    module Filesystem
      def size(style_name = default_style)
        if original_filename
          File.size(path(style_name))
        else
          false
        end
      end
    end

    module S3
      def size(style = default_style)
        if original_filename
          s3_object(style).content_length
        else
          false
        end
      rescue Aws::Errors::ServiceError => e
        false
      end
    end
  end
end

The paperclip-meta gem does appear to have a size method, in addition to image dimensions, aspect ratio, etc. I’m not sure if it’s a more recent addition than when you tried it. It has the advantage of caching the values in the DB.

Upvotes: 1

Related Questions