ahmet
ahmet

Reputation: 5005

How do I get the contents of temp file through a form

index.html.erb

= form_for :file_upload, :html => {:multipart => true} do |f|
      = f.label :uploaded_file, 'Upload your file.'
      = f.file_field :uploaded_file
      = f.submit "Load new dictionary"

Model

def file_upload
    file = Tempfile.new(params[:uploaded_file])
    begin
        @contents = file
    ensure
        file.close
        file.unlink   # deletes the temp file
    end
end

Index

def index
    @contents
end

But nothing is getting printed in my page after I upload a file = @contents

Upvotes: 8

Views: 9884

Answers (2)

Anand Shah
Anand Shah

Reputation: 14913

One way to fix the problem is to define the file_upload as a class method and call that method in the controller.

index.html.erb

= form_for :index, :html => {:multipart => true} do |f|
      = f.label :uploaded_file, 'Upload your file.'
      = f.file_field :uploaded_file
      = f.submit "Load new dictionary"

Model

def self.file_upload uploaded_file
  begin  
    file = Tempfile.new(uploaded_file, '/some/other/path')        
    returning File.open(file.path, "w") do |f|
      f.write file.read
      f.close
    end        
  ensure
    file.close
    file.unlink   # deletes the temp file
  end

end

Controller

def index
  if request.post?  
    @contents = Model.file_upload(params[:uploaded_file])
  end
end

You'll need to apply sanity checks and stuff. Now that @contents is defined in the Controller, you can use it in the View.

Upvotes: 0

aromero
aromero

Reputation: 25761

Use file.read to read the content of the uploaded file:

def file_upload
  @contents = params[:uploaded_file].read
  # save content somewhere
end

Upvotes: 8

Related Questions