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 %>
我該怎麼辦?在此先感謝
此表單不應該是多部分表單嗎? –
這是教程中的多部分形式,不能上傳沒有多部分形式的文件,所以是的。我應該是多部分。 –