class UpfileController < ApplicationController def index # @dir = get_local_list @files = Upfile.find(:all, :order => 'created_at desc') end def save_file if params['filename'].nil? or params['filename'] == '' flash[:error] = "沒有檔名!" redirect_to :action => 'index' return end # 取一個獨一的代表檔名 @filetoken = gettoken # 原始檔名 filename = params['filename'].original_filename # 指定將存到的位置及檔名 filewhere = "/home/ironman/test1/FILES/#{@filetoken}" # 真正的儲存動作 File.open("#{filewhere}", "wb") do |f| f.write(params['filename'].read) end # 讀出該檔的格式、大小為何 @content_type = get_content_type(filewhere) @size = File.size(filewhere) # 上述所得的檔案資訊存到 table 裡 Upfile.new Upfile.create(:filename => filename, :filetoken => @filetoken, :filetype => @content_type, :size => @size) flash[:notice] = "檔案上傳成功! #{@content_type} :: #{@size}" redirect_to :action => 'index' # 單純上傳的例子 # filename = params['filename'].original_filename # filewhere = "/home/ironman/test1/public/upload/#{filename}" # File.open("#{filewhere}", "wb") do |f| # f.write(params['filename'].read) # end # flash[:notice] = "檔案上傳成功,檔名 #{filename}" # redirect_to :action => 'index' end def dl @dlfile = Upfile.find_by_filetoken(params[:filetoken]) # 如果query的網址,在資料庫中沒此筆資料則中止下載動作 if @dlfile.nil? flash[:error] = "沒有這個檔案" redirect_to :action => 'index' return end # 若無上述中止動作則開始將檔名 send_file("/home/ironman/test1/FILES/#{@dlfile.filetoken}", :filename => "#{@dlfile.filename}", :type => "#{@dlfile.filetype}", :stream => true, :disposition => "attachment") # :disposition => "inline") end def rmfile @dlfile = Upfile.find_by_filetoken(params[:filetoken]) # 若沒該檔就中止動作,返回首頁 if @dlfile.nil? flash[:notice] = "no such file" redirect_to :action => 'index' return end # 若無上述中止動作則開始將刪檔及從資料庫中移掉該項目 File.delete("/home/ironman/test1/FILES/#{@dlfile.filetoken}") @dlfile.destroy flash[:notice] = "#{@dlfile.filename} 已順利刪除!" redirect_to :action=> 'index' end private def gettoken filetoken=Digest::SHA1.hexdigest(Time.now.to_s.split(//).sort_by {rand}.join) return filetoken end def get_content_type(filewhere) content_type = `file -bi "#{filewhere}"`.chomp content_type = fallback unless $?.success? content_type.gsub!(/;.+$/,"") if content_type return content_type end def get_local_list @dir = [] dir = Dir.open('./public/upload') dir.sort.each do |d| if d !~ /^\.*$/ @dir << d end end dir.close return @dir end end