Using Send_File to a Remote Source (Ruby on Rails)

后端 未结 3 609
再見小時候
再見小時候 2020-12-08 08:37

In my app, I have a requirement that is stumping me.

I have a file stored in S3, and when a user clicks on a link in my app, I log in the DB they\'ve clicked the lin

3条回答
  •  一个人的身影
    2020-12-08 09:17

    You would need to stream the file content to the user while reading it from the S3 bucket/object.

    If you use the AWS::S3 library something like this may work:

     send_file_headers!( :length=>S3Object.about(, )["content-length"], :filename=> )
     render :status => 200, :text => Proc.new { |response, output|
       S3Object.stream(, ) do |chunk|
         output.write chunk
       end
     }
    

    This code is mostly copied form the send_file code which by itself works only for local files or file-like objects

    N.B. I would anyhow advise against serving the file from the rails process itself. If possible/acceptable for your use case I'd use an authenticated GET to serve the private data from the bucket.

    Using an authenticated GET you can keep the bucket and its objects private, while allowing temporary permission to read a specific object content by crafting a URL that includes an authentication signature token. The user is simply redirected to the authenticated URL, and the token can be made valid for just a few minutes.

    Using the above mentioned AWS::S3 you can obtain an authenticated GET url in this way:

     time_of_exipry = Time.now + 2.minutes
     S3Object.url_for(, ,
                      :expires => time_of_exipry)
    

提交回复
热议问题