Skip to content

Instantly share code, notes, and snippets.

@szabcsee
Last active December 1, 2020 00:10
Show Gist options
  • Save szabcsee/8523329 to your computer and use it in GitHub Desktop.
Save szabcsee/8523329 to your computer and use it in GitHub Desktop.
Sinatra delivers data as json and deliver data in csv as attachment
require 'sinatra'
require 'json'
require 'csv'
# Serve data as JSON
get '/hi/:name' do
name = params[:name]
content_type :json
{ :message => name }.to_json
end
# Serve data as CSV file
get '/csv' do
content_type 'application/csv'
attachment "myfilename.csv"
csv_string = CSV.generate do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
# ...
end
end
# Upload form
get '/upload' do
erb :upload
end
# Handle POST-request (Receive and save the uploaded file and line by line load its content to an array.)
post '/upload' do
content = params['myfile'][:tempfile].read
content_arr = []
content.each_line do |line|
content_arr << line
end
puts content_arr
return "The operation has been successful! The uploaded csv content is in an array."
end
@dylankb
Copy link

dylankb commented Jan 27, 2016

This saved my ass. Thank you!

@yossi-shasho
Copy link

Thanks!

@palanisamy-hari
Copy link

thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment