Upload and download files in Sinatra

List

get '/' do
  list = Dir.glob("./files/*.*").map{|f| f.split('/').last}
  # render list here
end

Upload

post '/' do
  tempfile = params['file'][:tempfile]
  filename = params['file'][:filename]
  File.copy(tempfile.path, "./files/#{filename}")
  redirect '/'
end

Download

get '/download/:filename' do |filename|
  send_file "./files/#{filename}", :filename => filename, :type => 'Application/octet-stream'
end

Delete

get '/remove/:filename' do |filename|
  File.delete("./files/#{filename}")
  redirect '/'
end
Tags: ruby sinatra