引用:
原帖由 dong123qwe 于 2008-3-24 22:43 发表 
Rails应用的文件上传,(ex,上传图片),存入mysql里面,并在一个模板里显示图片.
下列代码允许用户上传一幅图片,并将图片和评论(comment)一道显示出来,为此我们先建一张pictures表来存储这些数据.
../migrate/003_create_pictures.rb
class CreatePictures < ActiveRecord: :Migration
def self.up
create_table :pictures do | t |
t.column :comment, :string
t.column :name, :string
t.column :content_type, :string
#if using MySQL, blobs deault to 64k, so we have to give an explicit size to extend them
t.column :date, :binary, :limit =>1.megabyte
end
end
def self.down
drop_table :pictures
end
end
创建一个处理图片上传的控制器:
../controllers/upload_controller.rb
class UploadController < ApplicationController
def get
@pictures = Pictures.new
end
end
get.rhtml模板.
../views/upload/get.rhtml
<%= error_messages_for("pictures") %>
<% 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 %>
这张表有一点微妙之处:上传的图片会被保存在uploaded_picture属性中,但数据库表里却没有这么个字段,也就是说,模型对象里必须做一些处理.
../models/picture.rb
class Picture < ActiveRecord :: Base
validates_format_of :content_type,
:with => /^image/,
:message => "--you can only upload pictures"
def upload_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)
File.basename(file_name).gsub(/[^\w._-]/ , ' ')
end
end
控制器中save()方法的实现也非常直观:
../controllers/upload_controller.rb
def save
@picture = Picture.new(params[ :picture])
if @picture.save
redirect_to (:action => 'show' , :id => @picture.id )
else
render (:action => :get)
end
end
我们现在已经把图片保存在数据库了,要怎么显示它呢?
../controllers/upload_controller.rb
def picture
@picture = Picture.find( params[:id])
send_data (@picture.data,
:filename => @picture.name,
:type => @picture.content_type,
:disposition => "inline")
end
最后只要实现个show()这个action,
def show
@picture = Picture.find( params[ :id] )
end
在模板中,我们用<img>标签指向显示图片内容的action.
<h3><%= @picture.comment %></h3>
<img src="<% =url_for(:action => 'picture' , :id => @picture.id) %>" />
后期将会点评,也希望大家来认真点评.