用ruby写了个文件服务器,实现简易的文件和文件夹浏览、下载的功能,主要代码如下
get '/*' do rootpath = "/home/baicai/" p = params["splat"][0] if p=='' or p==nil @currentpath = rootpath else @currentpath = rootpath+p+'/' end if File.directory? @currentpath files = Dir.entries @currentpath r_file = Array.new r_dir = Array.new files.each do |file| childpath = @currentpath+file childname = '' if p=='' or p==nil childname = file else childname = p+'/'+file end if file != '.' and file != '..' if File.directory? childpath r_dir.push Hash[:mtime => File.mtime(childpath), :size => '-', :filename => file+'/', :url => 'http://192.168.1.151:8001/'+childname] else r_file.push Hash[:mtime => File.mtime(childpath), :size => File.size(childpath), :filename => file, :url => 'http://192.168.1.151:8001/'+childname] end end end r_dir.sort! { |x, y| x[:filename] <=> y[:filename] } r_file.sort! { |x, y| x[:filename] <=> y[:filename] } @dirfiles = r_dir r_file.each do |r| @dirfiles.push r end @pagetitle = @currentpath[12, @currentpath.length] haml IO.read("views/filebrowser.haml") else content_type 'application/octet-stream' IO.read(@currentpath.chop!) end end
haml文件如下
!!! XML %html %head %title File Server %body{:bgcolor => "white"} %h1{:style => "font-family:Calibri,Arial,Microsoft YaHei"}= @pagetitle %hr %table{:border => "0"} %tr %th{:align => "left"} 文件名 %th{:width => "20"} %th{:align => "left"} 修改时间 %th{:width => "20"} %th{:align => "right"} 大小 -@dirfiles.each do |dirfile| %tr{:style => "font-family:Calibri,Arial,Microsoft YaHei;font-size:20px"} %td %a{:href => dirfile[:url]}= dirfile[:filename] %td %td= dirfile[:mtime].strftime("%Y-%m-%d %H:%M:%S") %td %td= dirfile[:size] %hr
效果如图: