rails文件上传下载和删除 .
Model中的部分:
class SystemUploadfile < ActiveRecord::Base
Region = ["北京","西安"]
File_extname = [".rar",".7z",".zip"]
File_target = "public/files"
cattr_accessor :per_page
@@per_page = 10
validates :title,:presence=>true
validates :area,:presence=>true
validates :file_name,:presence=>true
validates :file_url,:presence => true
validates_format_of :file_url,
:with => %r{/.(rar|zip|7z)}i
def set_file_values(file_url,file_name)
self.file_url = file_url
self.file_name = file_name
end
def add_download_count
self.counts += 1
self.save
end
def get_file_path
return SystemUploadfile::File_target+"/"+ self.file_url
end
#删除文件
def delete_file
file_path = File.join(Rails.root,SystemUploadfile::File_target,self.file_url)
if File.exist?(file_path)
File.delete(file_path)
end
end
end
Action中的部分如下:
class SystemUploadfilesController < ApplicationController
def index
@search = SystemUploadfile.search(params[:search]).order('id')
@system_uploadfiles = @search.paginate(:page => params[:page],:per_page => SystemUploadfile.per_page)
end
def new
@system_uploadfile = SystemUploadfile.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @system_uploadfile }
end
end
def create
#如果说什么也没有接收到
if request.get?
@system_uploadfile = SystemUploadfile.new
flash.now[:notice] = "文件上传失败"
render :action => "new"
else
@system_uploadfile = SystemUploadfile.new(params[:system_uploadfile])
#获取上传的文件
uploaded_file = params[:system_uploadfile][:file_url]
if_succ,filepath = upload_file(uploaded_file,SystemUploadfile::File_extname,SystemUploadfile::File_target)
if if_succ
@system_uploadfile.set_file_values(filepath, uploaded_file.original_filename)
if @system_uploadfile.save
redirect_to system_uploadfiles_path,:notice => "文件上传成功"
else
render :action => "new"
end
else
flash.now[:notice] = filepath
render :action => "new"
end
end
end
def download
@system_uploadfile = SystemUploadfile.find_by_id(params[:id])
if @system_uploadfile == nil
redirect_to system_uploadfiles_path, :notice => '没有记录,下载失败!'
else
file_path = @system_uploadfile.get_file_path
if File.exist?(file_path)
#@system_uploadfile.add_download_count
#send_file file_path,:disposition => 'inline'
io = File.open(file_path)
io.binmode
send_data(io.read,:filename => @system_uploadfile.file_name,:disposition => 'attachment')
io.close
else
redirect_to system_uploadfiles_path, :notice => '文件不存在,下载失败!'
end
end
end
def destroy
@system_uploadfile = SystemUploadfile.find_by_id(params[:id])
if @system_uploadfile == nil
flash.now[:notice] = '该记录已被删除'
redirect_to system_uploadfiles_path
else
@system_uploadfile.delete_file
@system_uploadfile.destroy
respond_to do |format|
format.html { redirect_to(system_uploadfiles_path) }
format.xml { head :ok }
end
end
end
end
Form:html部分
<% form_for( @system_uploadfile,:html=>{:multipart => true}) do |f| -%>
<%= f.label :title, "标题:" %>
<br />
<%= f.text_field :title%>
<em style="color:red;"><%= f.error_message_on :title %></em>
<br />
<%= f.label "区域" %>
<%= f.select :area,options_for_select(SystemUploadfile::Region) %>
<br></br>
选择上传文件:<br/>
<%= file_field(:system_uploadfile, :file_url)%>
<em style="color:red;"><%= f.error_message_on :file_url %></em>
<br/>
<%= f.submit "提交", :disable_with => '提交中...'%>
<% end -%>
程序中用到的一个方法:
def upload_file(file,extname,target_dir)
if file.nil? || file.original_filename.empty?
return false,"空文件或者文件名错误"
else
timenow = Time.now
filename = file.original_filename #file的名字
fileloadname = timenow.strftime("%d%H%M%S")+filename #保存在文件夹下面的上传文件的名称
if extname.include?(File.extname(filename).downcase)
#创建目录
#首先获得当前项目所在的目录+文件夹所在的目录
path = Rails.root.join(target_dir,timenow.year.to_s,timenow.month.to_s)
#生成目录
FileUtils.makedirs(path)
File.open(File.join(path,fileloadname),"wb") do |f|
f.write(file.read)
return true,File.join(timenow.year.to_s,timenow.month.to_s,fileloadname)
end
else
return false,"必须是#{extname}类型的文件"
end
end
end
from:http://blog.csdn.net/xuchao111/article/details/6333605