2014-05-13 83 views
1

我正在嘗試關注this tutorial。它寫在以前版本的Rails的,我用Rails 4.我想上傳文件,但我收到以下錯誤:Ruby Rails:上傳文件

NoMethodError in UploadController#uploadfile 
undefined method `[]' for nil:NilClass 

Extracted source (around line #3): 

class DataFile < ActiveRecord::Base 
    def self.save(upload) 
    name = upload['datafile'].original_filename 
    directory = "public/data" 
    # create the file path 
    path = File.join(directory, name) 

Rails.root: C:/Ruby193/mylibrary 

Application Trace | Framework Trace | Full Trace 
app/models/data_file.rb:3:in `save' 
app/controllers/upload_controller.rb:6:in `uploadfile' 

這裏是data_file.rb

class DataFile < ActiveRecord::Base 
    def self.save(upload) 
    name = upload['datafile'].original_filename 
    directory = "public/data" 
    # create the file path 
    path = File.join(directory, name) 
    # write the file 
    File.open(path, "wb") { |f| f.write(upload['datafile'].read) } 
    end 
end 

這裏是控制器upload_controller.rb

class UploadController < ApplicationController 
    def index 
    render :file => 'app\views\upload\uploadfile.html' 
    end 
    def uploadfile 
    post = DataFile.save(params[:upload]) 
    render :text => "File has been uploaded successfully" 
    end 
end 

這裏是uploadfile.html

<h1>File Upload</h1> 
<%= form_tag({:action => 'uploadfile'}, :multipart => true) do %> 
<p><label for="upload_file">Select File</label> 
    <%= file_field 'upload', 'datafile' %></p> 
<%= submit_tag "Upload" %> 
<% end %> 

我該怎麼辦?在此先感謝

+0

此表單不應該是多部分表單嗎? –

+0

這是教程中的多部分形式,不能上傳沒有多部分形式的文件,所以是的。我應該是多部分。 –

回答

1

它看起來像params [:上傳]是不是你認爲它是。您忘記將表單設置爲多部分。如果修復不起作用,請開始檢查參數以查看您實際獲得的內容。

def uploadfile 
    puts params.inspect # Add this line to see what's going on 
    post = DataFile.save(params[:upload]) 
    render :text => "File has been uploaded successfully" 
end 

而且,它不是一個偉大的「的回答,」但我一直在使用paperclip來處理文件上傳有很好的成功。如果你只是想要一些有用的東西(而不是自己學習如何做),請檢查一下。