views:

23

answers:

1

So Im trying to implement a file upload functionality where when a user uploads a file, I can read that into a File object and process it accordingly:

def create
  name = params[:upload]['datafile'].original_filename
  directory = "public/data"

   # create the file path
   path = File.join(directory, name)

   # read the file
      File.open(params[:upload][:datafile], 'rb') { | file |
         # do something to the file  
    }    
end

It throws an error with "can't convert Tempfile into String" on the File.open when I try to read the file.

What am I missing ?

+1  A: 

This means that params[:upload][:datafile] is already a file, so you do not need to give it to File.open. your code should be:

def create
  name = params[:upload]['datafile'].original_filename
  directory = "public/data"

   # create the file path
   path = File.join(directory, name)

   file = params[:upload][:datafile]
   # do something to the file, for example:
   #    file.read(2) #=> "ab"
end
Adrian