Last Updated: February 25, 2016
·
6.859K
· alfuken

Upload and download files in Sinatra

A simple example.

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