上传图片的问题(不用插件)

这几天公司让做一个在线的照片展示系统用来测试两个星期的RoR自学成果,在做到上传照片时,因为是按照<<Web 敏捷开发>>来开发的,书上是将图片保存在数据库中,也就是说在数据库表建立一个名为data,类型为binary的字段,可以成功保存.
可是将图片文件保存到数据库中占有太多的物理空间,并且速度慢,所以改为在数据库中存放图片的url,将图片存放到public/images/目录下,在这里没有使用其他的插件,
在getpicture.rhtml中写下如下的代码
<html>
<head>
<center>
<h1>Select Your Picture and Upload</h1>
</center>
</head>
<body>
<center>
<%= error_messages_for("picture") %>
<% form_for(:picture,
:url => { :action => 'savepicture'},
:html => { :multipart => true }) do |form| %>
Comment: <%= form.text_field("comment") %>
<br/>
Upload Your picture: <%= form.file_field("uploaded_picture") %>
<br/>
<%= submit_tag("Upload file") %>
<%= link_to "Back",{:action => "adminlist"} %>
<% end %>
</center>
</body>
</html>


上传的图片会被保存在uploaded_picture属性中,但数据库理没有这么一个字段,所以在模型对象里做如下设置


def uploaded_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
self.image_url = "/images/" + self.name

File.open("#{RAILS_ROOT}/public/images/#{picture_field.original_filename}", "wb+") do |f|
f.write(picture_field.read)
end
end

def base_part_of(file_name)
File.basename(file_name).gsub(/[^\w._-]/, '')
end

利用File.open一行将图片文件复制到public/images/目录下,并保存了该图片的url


在页面显示的时候直接用
<img src="<%= @picture.image_url%>" width="400" height="400"/>
就可以显示出图片了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值