How to get file stream in the output of Object.get

2019-09-14 02:44发布

I a writing a Rails API, with help of aws-sdk-ruby, which retrieves a file from AWS and returns in the response of API. Can I get somehow file stream in response of object.get, which I can directly return from the Rails API.

s3 = Aws::S3::Resource.new
bucket_name = "my_bucket"
bucket = s3.bucket(bucket_name)
object = bucket.object("a/b/my.pdf")
Rails.logger.info 'Downloading file to AWS'
downloaded_data = object.get({})
send_data(downloaded_data,
    :filename => "my.pdf",
    :type => "mime/type"
)

But it does not return file.

One option I know is to first save the file in local using this line:

object.get(response_target: '/tmp/my.pdf')

Than I can return this file but is there a way to skip this step and directly return the response of object.get without saving in local.

I can not use this solution as my URL are not public and I am just creating a REST API.

I got screen like following when I tried this solution.

enter image description here

1条回答
ら.Afraid
2楼-- · 2019-09-14 03:22

As of now what I am doing is getting a URL from the object like this:

url = object.presigned_url(:get, expires_in: 3600)

and using following code to send the response:

data = open(url)
send_data data.read, filename: file_name, type: "mime/type"
查看更多
登录 后发表回答