ruby 代码
- 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 代码
注:引自Dave Thomas的《Agile Web Development with Rails》