summaryrefslogtreecommitdiff
path: root/file_upload.rb
blob: b9a6d6da2e31b63be483e16a29a5f1030201aea4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# encoding: utf-8

require 'rubygems'
require 'haml'
require 'pathname'
require 'sinatra/base'

class FileUpload < Sinatra::Base
  configure do
    enable :static
    enable :sessions
    
    set :views, Pathname.new(__FILE__).dirname.join('views').expand_path
    set :public, Pathname.new(__FILE__).dirname.join('public').expand_path
  end
  
  helpers do
    def flash(message = '')
      session[:flash] = message
    end
  end
  
  not_found do
    haml '404'
  end
  
  error do
    haml "Error (#{request.env['sinatra.error']})"
  end
  
  get '/' do
    @files = settings.public.join('files').entries - [Pathname('.'), Pathname('..')]
    
    @flash = session[:flash]
    session[:flash] = nil
    
    haml :index
  end
  
  post '/upload' do
    if params[:file]
      filename = params[:file][:filename]
      file = params[:file][:tempfile]
      
      File.open(settings.public.join('files', filename), 'wb') {|f| f.write file.read }
      
      flash 'Uploaded successfully'
    else
      flash 'You have to choose a file'
    end
    
    redirect '/'
  end
end