1

Guy now i want to upload file with rails 4 my problem now i can't check the file extension before upload it

Note : I can upload the file well but i want to get the file kind before upload it

because i need the extension in another step in my App.

I'm tried to use the commands

File.extname(params[:Upload])

but always got the error

can't convert ActionDispatch::Http::UploadedFile into String

also how i can get the file base name before upload it ?? when i tryed to use

File.basename(params[:Upload])

i got the same error

can't convert ActionDispatch::Http::UploadedFile into String

also when i tried to convert the name to Sting i don't get any thing

asgeo1
  • 9,028
  • 6
  • 63
  • 85
Astm
  • 1,519
  • 2
  • 22
  • 30

2 Answers2

6

That's because File.extname expects a string file name, but an uploaded file (your params[:upload] is an object, it's an instance of the ActionDispatch::Http::UploadedFile class (kind of a temporary file)

To fix the problem you need to call the path property on your params[:upload] object, kind of like that

File.extname(params[:Upload].path)

Btw, if you're trying to get the type of the uploaded file, I'd encourage you to check for the params[:Upload].content_type instead, it's harder to spoof

Nikolay
  • 1,392
  • 1
  • 9
  • 15
0

You can use this:

params[:Upload].original_filename.split('.').last

The original_filename contains full filename with extension.

so you split it based on '.' and last index will contain the file extension.

For Example: "my_file.doc.pdf".split('.').last # => 'pdf'

You can check this for more info ActionDispatch::Http::UploadedFile.

Touqeer
  • 583
  • 1
  • 4
  • 19