Reputation: 2339
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.
I have found no solution to do that inside the model
I have installed paperclip-meta
gem but this gem is actually returning styles dimensions, not file size.
I might be able to retrieve the file size after the files have been uploaded to S3. I have read something about sending an Http header request or such and parsing return. I am not very at ease with this and it seems a bit complicate as the files have been generated locally and should be accessible by the server at some point.
Upvotes: 1
Views: 485
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