Reputation: 3469
I have an app where users can upload a csv and then play around with the data. Right now the csv is getting uploaded to my rails app's public folder on heroku but I want to send it to s3 b/c heroku isn't good with user uploaded files. Here's the code in my controller where I'm saving the csv directly to heroku:
File.open(Rails.root.join(
'public',
'user_files',
csv_name + '.csv'
), 'w') do |file|
file.write(output_csv_file)
end
How do I alter this code, as well as any other code I need to change in rails, to send this file to my aws bucket in s3? I've installed the 'aws-sdk' gem in my Gemfiles. I've also set the proper environment variables in heroku for my bucket. That's all I've done so far... Really lost.
Upvotes: 1
Views: 1314
Reputation: 76774
I don't know if this will help, but it may give you some ideas
Paperclip
The way our team uploads files with Rails is to use the amazing Paperclip
gem. I mention this because not only does Paperclip integrate with S3, but it also gives you a central way to manage your files correctly
Paperclip works with ActiveRecord (your db) to store the file information. You can then define in Paperclip's config options where the files are stored (S3 included). This means that if you're uploading a .csv file & allowing users to change it, using something like Paperclip will help you keep it in order correctly
Although you may or may not benefit from Paperclip, here's an overview of how it works:
Uploading With Paperclip
There's a good Railscast about Paperclip here
Here's how to get it working:
#app/models/csv.rb
class CSV < ActiveRecord::Base
has_attached_file :attachment
end
#app/controllers/csv_controller.rb
def create
@csv = CSV.new(CSV_params)
@csv.save
end
#app/views/csv/new.html.erb
<%= form_for @csv do |f| %>
<%= f.file_field :attachment %>
<% end %>
Using Paperclip with S3
There is a great tutorial on Heroku about Paperclip & S3
Here is some live code on how to get Paperclip working with S3:
#app/config/application.rb -> can use /environments/production.rb if you wish
config.paperclip_defaults = {
:storage => :s3,
:s3_host_name => 's3-eu-west-1.amazonaws.com'
}
#app/config/models/csv.rb
has_attached_file :image,
:styles => { :medium => "x300", :thumb => "x100" },
:default_url => "http://images.apple.com/iphone-5s/home/images/smart_hero.png",
:storage => :s3,
:bucket => 'firststop',
:s3_credentials => S3_CREDENTIALS
This is an overview of how you can get Paperclip working with Rails & S3. If it sounds like something you could benefit from, let me know & we can work to get it implemented in your app
Upvotes: 2