6

index.html.erbWie bekomme ich den Inhalt der temporären Datei über ein Formular

= 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" 

Modell

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 

Aber nichts gedruckt wird immer in meinem Seite nach dem Hochladen einer Datei = @contents

Antwort

4

Verwenden file.read den Inhalt der hochgeladenen Datei zu lesen:

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

Wie kann ich den Inhalt zurück zum Index senden – ahmet

0

Eine Möglichkeit, das Problem zu beheben, um die file_upload als Klassenmethode zu definieren und diese Methode in der Steuerung aufrufen.

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" 

Modell

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 

Sie werden Plausibilitätsprüfungen und Sachen anwenden müssen. Jetzt, wo @contents im Controller definiert ist, können Sie es in der Ansicht verwenden.