0

我正在编写一个应用程序来在 Amazon S3 上存储文件。我非常接近,我能够使用 url 保存和检索文件。但是,由于这些链接是公开的,我试图在我的 assetscontroller 中使用以下方法从 S3 检索存储的文件。

作为链接,可以在浏览器中查看/访问这些文件,但如果我使用此代码:

#This action will let the users download the files (after a simple authorization check)
def get
  asset = current_user.assets.find_by_id(params[:id])
  if asset
  #Parse the URL for special characters first before downloading  
  data = open("#{URI.parse(URI.encode(asset.uploaded_file.url))}")
  #then again, use the "send_data" method to send the above binary "data" as file.  
   send_data data, :filename => asset.uploaded_file_file_name 

 else
   flash[:error]="Access Violation"
   redirect_to assets_path
 end

结尾

我在浏览器中收到此错误:

Errno::ENOENT in AssetsController#get
No such file or directory - http://s3.amazonaws.com/BUCKETNAME/assets/29/FILENAME.jpeg?    1339979591

当我在登录 S3 管理控制台时单击 S3 站点上的资源时,该文件显示在我的浏览器中,其链接为

https://s3.amazonaws.com/BUCKETNAME/assets/29/FILENAME.jpeg?     AWSAccessKeyId=XXXXXXXXXXXExpires=1340003832&Signature=XXXXXXXXXXXXXXXXXX-amz-security-      token=XXXXXXXXX//////////XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

所以它确实存在但无法通过我的应用程序访问

这是我的浏览器中的应用程序跟踪:

app/controllers/assets_controller.rb:99:in `initialize'
app/controllers/assets_controller.rb:99:in `open'
app/controllers/assets_controller.rb:99:in `get'

关于发生了什么的任何线索?

谢谢

4

1 回答 1

0

您也可以将用户重定向到 S3 上的文件。

你试一试

redirect_to asset.uploaded_file.url

而不是send_file. send_file需要一个本地文件的路径,然后由网络服务器使用。

如果你已经设置s3_permissions => :private,那么你需要调用

redirect_to asset.uploaded_file.expiring_url(10)

有趣的是,在您的错误消息中,它是 s3 中针对 https 的 http - 您也可以尝试将以下选项添加到模型的 has_attached_file

:s3_protocol => 'https' 

希望这可以帮助。

于 2012-07-02T15:35:28.133 回答