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| -%>
  <p>
    <label for="mugshot">Upload A Mugshot:</label>
    <%= f.file_field :uploaded_data %>
  </p>
  <p>
    <%= submit_tag 'Create' %>
  </p>
<% end -%>


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

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




本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/102271,如需转载请自行联系原作者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值