Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the size of an uploaded file in Ruby on Rails?

I am not using carrierwave or paperclip for my file upload. I want to find out the file extension and the size in bytes of a file that the user has uploaded? Any ideas on how I can achieve this?

like image 828
Jakcst Avatar asked May 15 '12 20:05

Jakcst


2 Answers

File.size(doc.filename)

Just throw the name of the file into the curly brackets and you should be set.

If you want KB/MB use:

number_to_human_size(File.size(doc.filename))

EDIT:

You can use the exact path or Pathname

1.9.3p125 :005 > x=Pathname.new("/usr/bin/ruby")
 => #<Pathname:/usr/bin/ruby> 
1.9.3p125 :006 > File.size(x)
 => 5488 

For extension:

File.extname("test.rb")         #=> ".rb"
like image 196
Abram Avatar answered Oct 10 '22 07:10

Abram


params[:file].size
File.extname(params[:file].original_name)

or params[:file].original_name.match(/\.(\S*)$/).try(:"[]",1)

like image 22
Yuri Barbashov Avatar answered Oct 10 '22 07:10

Yuri Barbashov