Allowing User to Download File from S3 Storage

核能气质少年 提交于 2019-11-28 05:05:11
santuxus

To make this work, I've just added a new action in the controller, so in your case it could be:

#routes
resources :events do
  member { get :download }
end

#index
<%= link_to 'Download Creative', download_event_path(event), class: "btn btn-info" %>

#events_controller
def download
  data = open(event.creative_url)
  send_data data.read, :type => data.content_type, :x_sendfile => true
end

EDIT: the correct solution for download controller action can be found here (I've updated the code above): Force a link to download an MP3 rather than play it?

To avoid extra load to your app (saving dyno's time in Heroku), I would rather do something like this: add this method to your model with the attachment:

def download_url(style_name=:original)
  creative.s3_bucket.objects[creative.s3_object(style_name).key].url_for(:read,
      :secure => true,
      :expires => 24*3600,  # 24 hours
      :response_content_disposition => "attachment; filename='#{creative_file_name}'").to_s
end

And then use it in your views/controllers like this:

<%= link_to 'Download Creative', event.download_url, class: "btn btn-info" %>
Jimmy Huang

Now in aws-sdk v2, there is a method :presigned_url defined in Aws::S3::Object, you can use this method to construct the direct download url for a s3 object:

s3 = Aws::S3::Resource.new
# YOUR-OBJECT-KEY should be the relative path of the object like 'uploads/user/logo/123/pic.png'
obj = s3.bucket('YOUR-BUCKET-NAME').object('YOUR-OBJECT-KEY')
url = obj.presigned_url(:get, expires_in: 3600, response_content_disposition: "attachment; filename='FILENAME'")

then in your views, just use:

= link_to 'download', url
event = Event.find(params[:id])
  data = open(event.creative.url)
  send_data data.read, :type => data.content_type, :x_sendfile => true, :url_based_filename => true
end

You need to set the "Content-Disposition" to "attachment" in your HTTP response header. I'm not a Rails developer - so just Google it and you'll see plenty of examples - but it probably looks something like this:

    :content_disposition => "attachment"

or

     ...
    :disposition => "attachment"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!