Skip to content

How to evaluate the size of a file upload in Ruby on Rails

Posted on 19 July 2006

Sometimes it's useful to show how large a file is on a wesite. If anything, showing the file size allows the user to guage roughly how long it's going to take to download/open it.

Fortunately the combination of ruby and rails make this easy:

number_to_human_size(File.size("#{doc.filename}"))

number_to_human_size is a rails number helper. It takes a number in bytes and formats it as a file size with KB, MB etc. to show how large it is.

File.size is a ruby method. It just evaluates the size of the file and returns it in bytes. Very handy for the number_to_human_size helper.

View the snippets archive ››

3 comments made

Peter commented on 18 Apr 08 at 03:43

Google’d this and it came up on your site! BINGO. Cheers mate.

Carlos commented on 09 Aug 08 at 09:28

Well I was looking for something else. But this came in handy anyway. Thanks

Sean Kibler commented on 02 Nov 08 at 02:33

I found this via Google. I think it was actually the first result. Great blog and nice clean site design, I love it.

Got something to say?

About

Paul is a Rails developer for Kyan web agency.

Checkout his ramblings about music, what he's listening to and his other random thoughts.

He also writes on the Kyan blog.

More snippets

Take a look in the archive

Need a website?

Your best bet is to contact Paul's employer. Make sure to check out the portfolio of work.

Hosting

I recommend hostingrails.com

Contact

my name at gmail.com