Rails中文件上传

目标:
将文件保存到指定的文件夹中,对它重命名,保存重命名后的文件名称

为了能使任何controller都能使用文件上传的功能,变将代码放置在application.rb中
Java代码 收藏代码

# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
before_filter :configure_charsets

def configure_charsets
@headers["Content-Type"]="text/html;charset=utf-8"
end

def uploadFile(file)
if !file.original_filename.empty?
#生成一个随机的文件名
@filename=getFileName(file.original_filename)
#向dir目录写入文件
File.open("#{RAILS_ROOT}/public/emag/upload/#{@filename}", "wb") do |f|
f.write(file.read)
end
#返回文件名称,保存到数据库中
return @filename
end
end

def getFileName(filename)
if !filename.nil?
require 'uuidtools'
filename.sub(/.*./,UUID.random_create.to_s+'.')
end
end
end

在页面中,我们定义一<%=file_field "object","field"%>
Java代码 收藏代码

<%=file_field 'book','bgImage'%>

然后在对应的controller中调用即可
Java代码 收藏代码

def create
if request.get?
@book=Book.new
else
@book=Book.new(params[:book])
@book.bgImage=uploadFile(params[:book]['bgImage'])
if @book.save
redirect_to_index
end
end
end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值