我正在尝试建立一个非常基本的系统来将文件上传到我的rails 3.1应用程序。在人们开始向我扔回形针和载波链接之前,让我说这不是我正在寻找的解决方案。我已经阅读了关于这个主题的一些帖子,但是,我看到的所有代码要么在 rails 3.1 中被贬低,要么我只是不明白人们是如何解决这个问题的。
更新的视图/形式:(haml)
%h1 File Upload
= form_for :upload,:url=>{:action => 'uploadFile'},:html => { :multipart => true } do |f|
%p
%label{:for => "upload_file"} Select File
\:
\#{f.file_field 'datafile'}
= f.submit "Upload"
更新的控制器:
class UploadController < ApplicationController
def index
render :file => 'upload/uploadfile.haml'
end
def uploadFile
file_param = params[:upload][:datafile]
post = DataFile.save(file_param)
render :text => "File has been uploaded successfully"
end
end
更新模型
class DataFile < ActiveRecord::Base
def self.save(upload)
# Changed Default Destination: [__RAILS_DIR__/public/data]
name = "public/data/" + upload.original_filename
# can haz data directory?
require 'FileUtils'
FileUtils.mkdir_p(File.dirname(name))
File.open(name, "wb") { |f| f.write(upload.read) }
end
end
解决方案:
以上是我用来向我的 rails 3.1 应用程序添加简单上传功能的正确代码