Reputation: 5005
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
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
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