我正试着跟随本教程。它是用以前版本的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 %>我该怎么办?提前感谢
发布于 2014-05-13 04:11:17
它看起来像平面图:上传不是你想的那样。您忘记将表单设置为多部分。如果修复不起作用,就开始检查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而且,这不是一个很好的“答案”,但我在使用回形针处理文件上传方面取得了很好的成功。如果你只想要一些有用的东西(而不是自己学习),那就去看看吧。
https://stackoverflow.com/questions/23621704
复制相似问题