Allowing User to Download File from S3 Storage

前端 未结 5 1064
悲&欢浪女
悲&欢浪女 2020-12-08 05:57

Right now I am using Amazon S3 and Paperclip which is allowing my users to upload an image that is associated with the event they are creating. My ultimate goal is since oth

相关标签:
5条回答
  • 2020-12-08 06:21

    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?

    0 讨论(0)
  • 2020-12-08 06:25

    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"
    
    0 讨论(0)
  • 2020-12-08 06:27

    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" %>
    
    0 讨论(0)
  • 2020-12-08 06:29

    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
    
    0 讨论(0)
  • 2020-12-08 06:35
    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
    
    0 讨论(0)
提交回复
热议问题