简体   繁体   English

使用rails创建一个带有rails的下载链接到外部文件

[英]create a download link with rails to an external file with at URL

I moved my file storage to Rackspace Cloudfiles and it broke my send_file action. 我将文件存储移动到Rackspace Cloudfiles,它破坏了我的send_file操作。

old

def full_res_download
  @asset = Asset.find(params[:id])
  @file = "#{Rails.root}/public#{@asset.full_res}"
  send_file @file
end

new

def full_res_download
  @asset = Asset.find(params[:id])
  @file = "http://86e.r54.cf1.rackcdn.com/uploads/fake/filepath.mov"
  send_file @file
end

When the files were in the public file. 当文件在公共文件中时。 the code worked great. 代码工作得很好。 When you click in the link the file would download and the webpage would not change. 当您单击链接时,文件将下载并且网页不会更改。 Now it gives this error. 现在它给出了这个错误。

Cannot read file http://86e.r54.cf1.rackcdn.com/uploads/fake/filepath.mov

What am i missing? 我错过了什么?

Thank you so much for your time. 非常感谢您的参与。

send_file opens a local file and sends it using a rack middleware. send_file打开一个本地文件并使用机架中间件发送它。 You should just redirect to the url since you're not hosting the file anymore. 您应该只是重定向到网址,因为您不再托管该文件。

As one of the comments points out, in some situations you may not be able to use a redirect, for various reasons. 正如其中一条评论所指出的,在某些情况下,由于各种原因,您可能无法使用重定向。 If this is the case, you would have to download the file and relay it back to the user after retrieving it. 如果是这种情况,则必须下载该文件并在检索后将其转发回用户。 The effect of this is that the transfer to the user would do the following: 这样做的结果是转移给用户将执行以下操作:

  1. Request gets to your server, processing in your action begins. 请求到达您的服务器,开始处理您的操作。
  2. Your action requests the file from the CDN, and waits until the file has been fully retrieved. 您的操作从CDN请求文件,并等待文件完全检索。
  3. Your server can now relay the file on to the end user. 您的服务器现在可以将文件中继到最终用户。

This is as compared to the case with a redirect: 这与重定向的情况相比:

  1. Request gets to your server, processing in your action begins. 请求到达您的服务器,开始处理您的操作。
  2. Your action redirects the user to the CDN. 您的操作会将用户重定向到CDN。

In both cases the user has to wait for two full connections, but your server has saved some work. 在这两种情况下,用户都必须等待两个完整连接,但是您的服务器已经保存了一些工作。 As a result, it is more efficient to use a redirect when circumstances allow. 因此,在环境允许的情况下使用重定向会更有效。

what worked 什么工作

def full_res_download
  @asset = Asset.find(params[:id])
  @file = open("http://86e.r54.cf1.rackcdn.com/uploads/fake/filepath.mov")
  send_file( @file, :filename => File.basename(@asset.file.path.to_s))
end

real code 真实的代码

controler.rb controler.rb

def web_video_download
  @asset = Asset.find(params[:id])
  @file = open(CDNURL + @asset.video_file.path.to_s)
  send_file( @file, :filename => File.basename(@asset.video_file.path.to_s))
end

development.rb development.rb

CDNURL = "http://86e.r54.cf1.rackcdn.com/"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM