Ruby on Rails send_file在刷新页面之前不起作用?

时间:2014-05-08 12:13:45

标签: ruby-on-rails ruby ruby-on-rails-4 delay sendfile

我正在使用Rails服务器,我可以从中下载本地存储的电影和动漫等。这有点工作,但是当我点击下载链接时,我必须刷新页面才能真正开始下载。

这是处理下载的控制器:

class DownloadController < ApplicationController
  def index
    @title = params[:title]
    @name = params[:name]
    @path = '/media/sf_Anime,_VN,_LN/Watching, not watched yet/'+@title+'/'+@name
    send_file( @path )
  end
end

这是链接到该控制器的链接:

<% @episodes.each do |x| %>
<p> <%= x %><%= link_to " Download", 
    {controller: 'download', action: 'index', title: @title, name: x } %> </p>
<% end %>

修改 我今天做了一些测试,并注意到如果我尝试发送较小的文件(文本或图像),下载链接会立即生效。我还注意到下载链接实际上适用于电影,但下载开始需要20-30秒。 你知道会导致这种延迟的原因吗?

4 个答案:

答案 0 :(得分:3)

你在使用turbolinks吗? Turbolinks显然不能与send_file(https://github.com/rails/turbolinks/issues/182)很好地配合。尝试添加&#34;数据:{no-turbolink:true}&#34; (或&#34;&#39; data-no-turbolink&#39; =&gt; true&#34;)在link_to帮助器中,例如:

<%= link_to "Downloadable File", downloadable_file, data: { no-turbolink: true } %>

另请参阅:Rails 4, asset pipeline causes user downloadable files to be downloaded twicerails won't send_data as fileRuby on Rails send_file, code in controller action running twice

答案 1 :(得分:0)

编辑以反映以下评论。我会简单地添加一个关注处理下载,然后使用

include Concerns::Downloads

处理您的下载请求。 routes.rb看起来像这样。

resources :movies do
member do
  post 'download'
end

并在视图中

  <%= link_to 'Download', {:controller => 'movies', :action => 'download'}, {:method => :post } %></a>

答案 2 :(得分:0)

将文件移动到公共文件夹
仅将文件名添加到link_to

<%= link_to "Downloadable File", "/"+filename, %>

答案 3 :(得分:-1)

尝试在send_file

中设置对附件的处置
class DownloadController < ApplicationController
  def index
    ...
    send_file( @path, :disposition => 'attachment' )
  end
end

问题可能是您的浏览器正在尝试打开文件本身 - :disposition => 'attachment'会提示浏览器下载该文件,即使它认为该文件是可以打开的文件。

相关问题