rails中实现上传功能

在rails中实现上传文件的实现非常的简单
步骤:
通过一个例子来做(winxp,rails 1.2.5):
rails demo -d mysql
cd demo
mysqladmin -u root create demo_development
1.使用插件
安装attechment_fu插件:
ruby script/plugin install [url]http://svn.techno-weenie.net/projects/plugins/attachment_fu/[/url]

2.生成model

ruby script/generate model mugshot
3.编辑迁移文件001_create_mugshots.rb

class CreateMugshots < ActiveRecord::Migration
  
  def self.up
    create_table :mugshots do |t|
      t.column :parent_id,  :integer
      t.column :content_type, :string
      t.column :filename, :string    
      t.column :thumbnail, :string 
      t.column :size, :integer
      t.column :width, :integer
      t.column :height, :integer
    end
  end

  def self.down
    drop_table :mugshots
  end
end

----
4.执行迁移任务:
rake db:migrate
5.修改Model, mugshot.rb
class Mugshot < ActiveRecord::Base
  
  has_attachment :storage => :file_system
 

  validates_as_attachment

end


5.创建控制器:
ruby script/generate controller mugshots


class MugshotsController < ApplicationController
def new
  @mugshot = Mugshot.new
end

def create
  @mugshot = Mugshot.new(params[:mugshot])
  if @mugshot.save
    flash[:notice] = 'Mugshot was successfully created.'
    redirect_to :action=>"new"     
  else
    render :action => :new
  end
end

end


--创建new模板:
<%= error_messages_for :mugshot %>

<% form_for(:mugshot, :url => {:action=>"create"}, 
                      :html => { :multipart => true }) do |f| -%>
 


   
    <%= f.file_field :uploaded_data %>
 


 


    <%= submit_tag 'Create' %>
 


<% end -%>


--没什么问题应该可以运行了
ruby script/server
[url]http://localhost:3000/mugshots/new[/url]

上传的文件会保存在\public\mugshots中!




本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/102271,如需转载请自行联系原作者

你可能感兴趣的:(rails中实现上传功能)