简体   繁体   English

Ruby Rails:上传文件

[英]Ruby Rails: Upload File

I am trying to follow this tutorial . 我正在尝试按照本教程进行操作 It has written in previous version of Rails and I am using Rails 4. I am trying to upload file but I am getting following error: 它是在先前版本的Rails中编写的,并且我正在使用Rails4。我正在尝试上传文件,但是出现以下错误:

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'

Here is data_file.rb 这是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

Here is controller upload_controller.rb 这是控制器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

Here is uploadfile.html 这是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 %>

What should I do? 我该怎么办? Thanks in advance 提前致谢

It looks like params[:upload] isn't what you think it is. 看起来params [:upload]不是您想的那样。 You forgot to set the form to be multipart. 您忘记将表格设置为多部分。 If fixing that doesn't make it work, start inspecting params to see what you're actually getting. 如果无法解决问题,请开始检查参数以查看实际得到的内容。

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

Also, it's not a great "answer," but I've had good success using paperclip to handle file uploads. 另外,这不是一个很好的“答案”,但是使用回形针处理文件上传的工作取得了很好的成功。 If you just want something that works (rather than learning how to do it yourself), check into that. 如果您只是想要一些有用的东西(而不是自己学习如何做),请检查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM