http://rorwiki.hellopen.net/index.php?title=HowtosFiles

圖片上傳是web應(yīng)用程序中常用到的,ROR中是如何實(shí)現(xiàn)的。

1.創(chuàng)建一個(gè)表
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.建立一個(gè)controller

class UploadController < ApplicationController
?
?def get
??@picture = Picture
?end
?
end

3.頁(yè)面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%>
在這邊要注意的是要設(shè)置:multipart=>true.

4.建立實(shí)體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增加一個(gè)save方法

def save
?@picture = Picture.new(params[:picture])
?if @picture.save
??redirect_to(:action=>"show",:id=>@picture)
?else
??render(:action=>:get)
?end
end
這樣就把圖片存入到數(shù)據(jù)庫(kù)中了。那如何在頁(yè)面上現(xiàn)實(shí)圖片呢?

6.在controllers中增加一個(gè)picture的方法。

def picture
?@picture = Picture.find(params[:id])
?send_data(@picture.data,
???? :filename=>@picture.name,
???? :type=>@picture.content_type,
???? :disposition>"inline")
end

轉(zhuǎn)到顯示頁(yè)面的action就很簡(jiǎn)單了。

def show
?@picture = Picture.find(params[:id])
end

7.顯示圖片頁(yè)面show.rhtml

<h3><%=@picture.comment%></h3>
<image src="<%=url_for(:action=>"picture",:id=>@picture.id)%>"/>


?