http://rorwiki.hellopen.net/index.php?title=HowtosFiles
图片上传是web应用程序中常用到的,ROR中是如何实现的。
1.创建一个表
create table pictures(
id int not null auto_increment,
comment varchar(100),
name varchar(200),
content_type varchar(100),
data blob,
primary key(id)
);
2.建立一个controller
class UploadController < ApplicationController
def get
@picture = Picture
end
end
3.页面get.rhtml
<%=error_messages_for("picture")%>
<%=form_tag({:action=>"save",:multipart=>true})%>
comment:<%=text_field("picture","comment")%><br>
Upload your picture:<%=file_field("picture","picture")%><br>
<%=submit_tag("Upload file")%>
<%=end_form_tag%>
在这边要注意的是要设置:multipart=>true.
4.建立实体Picture.rb
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_file.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
5.在controller增加一个save方法
def save
@picture = Picture.new(params[:picture])
if @picture.save
redirect_to(:action=>"show",:id=>@picture)
else
render(:action=>:get)
end
end
这样就把图片存入到数据库中了。那如何在页面上现实图片呢?
6.在controllers中增加一个picture的方法。
def picture
@picture = Picture.find(params[:id])
send_data(@picture.data,
:filename=>@picture.name,
:type=>@picture.content_type,
:disposition>"inline")
end
转到显示页面的action就很简单了。
def show
@picture = Picture.find(params[:id])
end
7.显示图片页面show.rhtml
<h3><%=@picture.comment%></h3>
<image src="<%=url_for(:action=>"picture",:id=>@picture.id)%>"/>