Paperclip attachment file size
Asked Answered
C

4

6

How do I fetch the file size of each style of a paperclip attachment?

@user.attachment_file_size doesn't seem to work

@user.attachment(:style).size

gives a number not related to the actual file size

Caddaric answered 10/2, 2013 at 22:11 Comment(1)
Latest version of paperclip doesn't give me the file_size either. Not sure what's up.Verdha
T
6

I didn't find either how to get the file size for a given style, other than the original one.

As seen in the paperclip source code, @user.attachment.size returns the size of the file as originally assigned. There is no way to get it for a specific style...

A solution would be:

open(@user.attachment(:style)).size

But not efficient at all.

To do it well, you should probably add some "custom size" fields in your attachment table that you would fill once the attachment is saved for each style...

Trounce answered 21/9, 2014 at 18:9 Comment(1)
Hi Pierrea, probably no longer an issue for you. But I have found a solution answered below, by catching the temp file for each style before uploading to S3.Dalenedalenna
M
4

User find by ID(for example) User has :photo

@user.last.photo_file_size
Monkfish answered 12/2, 2013 at 13:42 Comment(0)
D
0

You can get a string like "WIDTHxHEIGHT" inside styles hash, for the giving object's style, using Paperclip::Style#geometry:

string = @user.attachment.styles[:size].geometry

Than you can split the string to have either height or width:

width = string.split("x")[0]

height = string.split("x")[1]
Dwightdwindle answered 20/6, 2015 at 23:26 Comment(0)
D
0

It seems it is possible actually

Just have to cath the temporary files for each style and applying size method.

let's say you have two styles large and small for your attachment called image and you have created two extra fields in your model large_size and small_size to save those values.

Just add the below bit of code to your model:

before_create :assign_sizes

private
def assign_sizes
    self.large_size = image.queued_for_write[:large].size.to_i
    self.small_size = image.queued_for_write[:small].size.to_i
end

The fields large_size and small_size will be popuated with each style file size. And this will be done before the files are sent to S3 for example. So there is no extra querying the files headers from S3.

Dalenedalenna answered 8/8, 2017 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.