summaryrefslogtreecommitdiff
path: root/file_upload.rb
blob: a23d6a14e916231fcb42aee5ac4d805ff85c4f97 (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
55
# encoding: utf-8

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

class FileUpload < Sinatra::Base
  configure do
    enable :static
    enable :sessions

    set :views,  File.join(File.dirname(__FILE__), 'views')
    set :public, File.join(File.dirname(__FILE__), 'public')
    set :files,  File.join(public, 'files')
  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 = Dir.entries(settings.files) - ['.', '..']

    @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(File.join(settings.files, filename), 'wb') {|f| f.write file.read }

      flash 'Uploaded successfully'
    else
      flash 'You have to choose a file'
    end

    redirect '/'
  end
end