簡體   English   中英

Ruby Rails:上傳文件

[英]Ruby Rails: Upload File

我正在嘗試按照本教程進行操作 它是在先前版本的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'

這是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 %>

我該怎么辦? 提前致謝

看起來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

另外,這不是一個很好的“答案”,但是使用回形針處理文件上傳的工作取得了很好的成功。 如果您只是想要一些有用的東西(而不是自己學習如何做),請檢查一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM