class CreatePictures < ActiveRecord::Migration def self.up create_table :pictures do |t| t.string :comment t.string :name t.string :content_type # If using MySQL, blobs default to 64k, so we have to give # an explicit size to extend them t.binary :data, :limit => 1.megabyte end end def self.down drop_table :pictures end end
2. 创建UploadController
class UploadController < ApplicationController def get @picture = Picture.new end def save @picture = Picture.new(params[:picture]) if @picture.save redirect_to(:action => 'show', :id => @picture.id) else render(:action => :get) end end def show @picture = Picture.find(params[:id]) end def picture @picture = Picture.find(params[:id]) send_data(@picture.data, :filename => @picture.name, :type => @picture.content_type, :disposition => "inline") end end
3. 文件上传初始页面get.html.erb
<%= error_messages_for("picture" ) %> <% form_for(:picture, :url => {:action => 'save'}, :html => { :multipart => true }) do |form| %> Comment: <%= form.text_field("comment" ) %><br/> Upload your picture: <%= form.file_field("uploaded_picture" ) %><br/> <%= submit_tag("Upload file" ) %> <% end %>
4. 上传后的从数据库中读取图片并显示图片的页面show.html.erb
<h3><%= @picture.comment %></h3> <img src="<%= url_for(:action => 'picture', :id => @picture.id) %>"/>
5. 访问http://localhost:3000/upload/get
![](http://dl.iteye.com/upload/attachment/0079/9111/cc2b7309-2c90-3280-a5ef-f40756ce747c.jpg)