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.

About Paul

Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.

Follow Paul on Twitter

Email: paulsturgess [at] gmail.com

Read more articles in the archive →

Comments...

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

    Peter at 18 Apr 08 at 03:43

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

    Carlos at 09 Aug 08 at 09:28

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

    Sean Kibler at 02 Nov 08 at 02:33

  • Only today really looked for this one and got here... It's been a while since posted but I just had to give you congrats, great finding! Best regards!

    Abraão Coelho at 08 Dec 08 at 18:10

  • Thanks,

    This is exactly what I need!

    Sincerely,
    Igor.
    http://www.MyTaskHelper.com

    Igor Pro at 31 Dec 08 at 03:12

  • nice one! exactly what I was looking for ;)
    thx

    maurizio de magnis at 04 Aug 09 at 09:58

  • was very helpful....

    Jeyant at 19 Aug 11 at 12:21

Got something to say?