6

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" 

モデル

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

インデックス

def index 
    @contents 
end 

しかし、何が私の中に印刷されていないばかりされて一時ファイルの内容を取得しますファイルをアップロードした後のページ= @contents

答えて

4

使用file.readアップロードされたファイルの内容を読むために:問題を修正する

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

コンテンツをインデックスに戻すにはどうすればよいですか – ahmet

0

一つの方法は、クラスメソッドとしてfile_uploadを定義し、コントローラにそのメソッドを呼び出すことです。

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" 

モデル

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 

コントローラ

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

あなたは健全性チェックやものを適用する必要があります。コントローラーで@contentsが定義されたので、これをビューで使用できます。