How to get the contents of a temporary 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 prints on my page after downloading the file = @contents

+6
source share
2 answers

Use file.read to read the contents of the downloaded file:

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

One way to fix the problem is to define file_upload as a class method and call this 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 will need to apply sanity checks and more. Now that @contents defined in the controller, you can use it in the view.

0
source

Source: https://habr.com/ru/post/945409/


All Articles