Last active
December 1, 2020 00:10
-
-
Save szabcsee/8523329 to your computer and use it in GitHub Desktop.
Sinatra delivers data as json and deliver data in csv as attachment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Thanks!
thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This saved my ass. Thank you!