Rich_F
Rich_F

Reputation: 2056

Ruby File Upload Size

I'm trying to test the size of an upload to validate its size. Outside of the upload algos, simply looking at the temp file is where I'm having the issue. I have a test file on my desktop named test1.png, which is 115 KB.

a = '/users/rich/desktop/test1.png'
s = File.open(a, 'wb')
r = File.size(a)
p r                         => 0
p s.size                    => 0

Not sure what I'm doing wrong here, but both resolve to 0. Not true.

How can I get the size of a file?

Upvotes: 0

Views: 101

Answers (1)

Gerry
Gerry

Reputation: 10507

The problem is the 'w' flag, since it truncates existing file to zero length, so, since you open the file before getting its size, you get 0.

To get the size you could just use the path of the file without using File.open:

a = '/users/rich/desktop/test1.png'
File.size(a)

Or, if you need to create the File object, just use the 'r' flag:

a = '/users/rich/desktop/test1.png'
s = File.open(a, 'r')

Now you can either use File.size(a) or s.size to get the size of the file.

Upvotes: 2

Related Questions