文件上传,页面代码:
<%form_tag '/project/add_attach',:multipart=>true do%>
<%=file_field 'path'%>
<%=submit '提交'%>
<%end%>
#文件上传处理,只需在数据库表中,记录路径就可以了,下面代码写在controller层:
name = Time.now.strftime("%y%m%d%I%M%S") + 'size'+ params[:path].size.to_s ##防止新文件名重复
suffix=File.extname("#{params[:path].original_filename}") #取旧文件名
name<<suffix
directory = "public/data"
path = File.join(directory, name) ##传换路径,格式:/public/data/xx.xx
File.open(path, "wb") { |f| f.write(upload.read) } ##写文件内容
params[:path]页面上传过来的一个file参数 (格式:与#<Action...>相似)
##下载文件,controller层:
def download
send_file params[:path] #只需传文件路径,格式:/public/data/xx.xx
end
##删除文件,写在model层(只须传一个文件名(xx.xx)):
def self.filedelete(name)
if File.exist?("#{File.dirname(__FILE__)}/../../public/data/#{name}")
File.delete("#{File.dirname(__FILE__)}/../../public/data/#{name}")
end
end