我正在尝试关注this tutorial。它已在Rails的早期版本中编写,我正在使用Rails 4.我正在尝试上传文件,但我收到以下错误:
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 :(得分:1)
看起来params [:upload]并不是你想象的那样。您忘记将表单设置为多部分。如果修复不能使其起作用,请开始检查参数以查看您实际获得的内容。
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
此外,它不是一个很好的回答,&#34;但是我使用paperclip来处理文件上传取得了很大的成功。如果你只想要一些有效的东西(而不是自己学习如何去做),请检查一下。