jdesilvio
jdesilvio

Reputation: 1854

Download file from S3 to Rails 4 app

I have an AWS VM that runs a daily task and generates several files. I want my Rails app to download these files and place them in a folder within the app. Is there a gem or method in Ruby that can do this?

I know how to do it in bash with s3cmd and I guess I could create a script to get them this way, but looking for a more native rails way.

I am using the data in these files for the app, but I don't want the users to be able to download them.

Upvotes: 7

Views: 17875

Answers (3)

Pooja Mane
Pooja Mane

Reputation: 487

You can use download_file method provided by aws-sdk.

s3 = Aws::S3::Resource.new(
  region: 'us-east-1',
  access_key_id: '...',
  secret_access_key: '...'
)
file_path = "file path name to download"
s3.bucket('bucket-name').object('key').download_file(file_path)

Upvotes: 2

wintondeshong
wintondeshong

Reputation: 1277

In the v1 aws-sdk, the code to download from s3 is...

File.open(local_file_path, "wb") do |file|
  s3_object(s3_key).read do |chunk|
    file.write(chunk)
  end
end

Upvotes: 0

Trevor Rowe
Trevor Rowe

Reputation: 6538

The aws-sdk v2 gem provides a simple interface for downloading objects from Amazon S3.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(
  region: 'us-east-1',
  access_key_id: '...',
  secret_access_key: '...'
)

s3.bucket('bucket-name').object('key').get(response_target: '/path/to/file')

Upvotes: 20

Related Questions