Rails2.2.2之文件上传下载

1. 创建一个保存文件的表,然后rake db:migrate同步到数据库
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
[img]http://dl.iteye.com/upload/attachment/0079/9111/cc2b7309-2c90-3280-a5ef-f40756ce747c.jpg[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值