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 

你需要申請完整性檢查之類的東西。現在在Controller中定義了@contents,您可以在View中使用它。