2006-12-03
rails 上传图片
关键字: railsruby 代码
- class CreatePictures < ActiveRecord::Migration
- def self.up
- create_table :pictures do |t|
- t.column :comment, :string, :limit=>100
- t.column :name, :string, :limit=>200
- t.column :content_type, :string, :limit=>100
- t.column :title, :binary
- end
- end
- def self.down
- drop_table :pictures
- end
- end
ruby 代码
- class RenameColumnData < ActiveRecord::Migration
- def self.up
- rename_column :pictures,:title, :data
- end
- def self.down
- rename_column :pictures,:data, :title
- end
- end
以上是通过migration建立相应的数据表。
建立controller:
ruby 代码
- class UploadController < ApplicationController
- def get
- @picture = Picture.new
- end
- end
建立get template:
ruby 代码
- <%= error_messages_for("picture") %>
- <%= form_tag({:action => 'save'}, :multipart => true) %>
- Comment: <%= text_field("picture", "comment") %>
- Upload your picture: <%= file_field("picture", "picture") %>
- <%= submit_tag("Upload file") %>
- <%= end_form_tag %>
建立model:
ruby 代码
- class Picture < ActiveRecord::Base
- validates_format_of :content_type, :with => /^image/,
- :message => "--- you can only upload pictures"
- def picture=(picture_field)
- self.name = base_part_of(picture_field.original_filename)
- self.content_type = picture_field.content_type.chomp
- self.data = picture_field.read
- end
- def base_part_of(file_name)
- name = File.basename(file_name)
- name.gsub(/[^\w._-]/, '')
- end
- end
扩充controller,添加save action:
ruby 代码
- def save
- @picture = Picture.new(params[:picture])
- if @picture.save
- redirect_to(:action => 'show', :id => @picture.id)
- else
- render(:action => :get)
- end
- end
扩充controller,添加picture action:
ruby 代码
- def picture
- @picture = Picture.find(params[:id])
- send_data(@picture.data,
- :filename => @picture.name,
- :type => @picture.content_type,
- :disposition => "inline")
- end
定义show action:
ruby 代码
- def show
- @picture = Picture.find(params[:id])
- end
显示图片:
ruby 代码
-
<%= @picture.comment %>
注:引自Dave Thomas的《Agile Web Development with Rails》
发表评论
- 浏览: 37204 次
- 性别:


- 详细资料
搜索本博客
最近加入圈子
最新评论
-
研究生监考
SVN还是还能有用的啊,你还没有进行程序开发的版本控制么
-- by kayo -
一个简单的RST实例
proper 写道使用 Rest 的方式的话,是不是这段http://127.0 ...
-- by 李超群 -
一个简单的RST实例
使用 Rest 的方式的话,是不是这段http://127.0.0.1:3000 ...
-- by proper -
Editplus编辑Rubby
不懂ruby,不过你可以去找找ruby.acp,或自己创建一个,自动完成代码,格 ...
-- by winhkey -
eclipse安装插件(以安装 ...
放在eclipse目录中的话,用相对路径就可以了 path=language ...
-- by winhkey






评论排行榜