6

index.html.erbLàm thế nào để có được nội dung của tập tin tạm thời thông qua một hình thức

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

Mẫu

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 

Nhưng không có gì là nhận in của tôi trang sau khi tôi tải lên một tệp = @contents

Trả lời

4

Sử dụng file.read để đọc nội dung của tập tin tải lên:

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

Làm cách nào để gửi nội dung trở lại chỉ mục – ahmet

0

Một cách để khắc phục vấn đề được xác định file_upload như một phương pháp học và gọi đó là phương pháp trong điều khiển.

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" 

Mẫu

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 

khiển

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

Bạn sẽ cần phải áp dụng kiểm tra sự tỉnh táo và các công cụ. Bây giờ, @contents được xác định trong Bộ điều khiển, bạn có thể sử dụng nó trong Chế độ xem.

Các vấn đề liên quan