使用 Send_File 到远程源 (Ruby on Rails) [英] Using Send_File to a Remote Source (Ruby on Rails)

查看:39
本文介绍了使用 Send_File 到远程源 (Ruby on Rails)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个让我难受的需求.

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

我有一个文件存储在 S3 中,当用户单击我的应用程序中的链接时,我登录他们单击该链接的数据库,将他们的下载信用"限额减少 1,然后我想提示下载文件.

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 link, decrease their 'download credit' allowance by one and then I want to prompt the file for download.

我不想简单地将用户重定向到文件,因为它存储在 S3 中,我不希望他们拥有源文件的链接(以便我可以保持完整性和访问权限)

I don't simply want to redirect the user to the file because it's stored in S3 and I don't want them to have the link of the source file (so that I can maintain integrity and access)

看起来 send_file() 无法处理远程源文件,有人推荐可以做到这一点的 gem 或合适的代码吗?

It looks like send_file() wont work with a remote source file, anyone recommend a gem or suitable code which will do this?

推荐答案

当从 S3 存储桶/对象读取文件内容时,您需要将文件内容流式传输给用户.

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

如果您使用 AWS::S3 库,这样的东西可能会起作用:

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

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

此代码主要是从 send_file 代码复制而来的,该代码本身仅适用于本地文件或类文件对象

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

注意无论如何,我建议不要从 rails 进程本身提供文件.如果您的用例可能/可接受,我将使用 经过身份验证的 GET 来提供存储桶中的私有数据.

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.

使用经过身份验证的 GET,您可以保持存储桶及其对象的私密性,同时通过制作包含身份验证签名令牌的 URL 来允许读取特定对象内容的临时权限.用户只需重定向到经过身份验证的 URL,令牌就可以在几分钟内有效.

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.

使用上面提到的 AWS::S3,您可以通过这种方式获取经过身份验证的 GET url:

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(<s3 object>, <s3 bucket>,
                  :expires => time_of_exipry)

这篇关于使用 Send_File 到远程源 (Ruby on Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆