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 ››

2 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

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com