6

index.html.erbJak uzyskać zawartość pliku tymczasowego za pośrednictwem formularza

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

modelu

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 

Ale nic nie jest uzyskiwanie drukowanej w moim strona po przesłaniu pliku = @contents

Odpowiedz

4

Zastosowanie file.read czytać treść przesłanego pliku:

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

Jak mogę wysłać zawartość z powrotem do indeksu – ahmet

0

Jednym ze sposobów, aby rozwiązać ten problem jest do zdefiniowania file_upload jako metoda klasy i wywołanie tej metody w kontrolerze.

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 

Musisz zastosować testów poprawności i rzeczy. Teraz, gdy w sterowniku zdefiniowano @contents, można go użyć w widoku.

Powiązane problemy