Rails - 在每个循环中使用send_file同时下载多个文件

问题描述 投票:0回答:1

我想在循环中为我的数组中的每个值下载一个文件。

我班上有两种方法:

def test
  testarray = ['value1', 'value2', 'value3']

  testarray.each do |value|
    download_file(value)
  end

end 

def download_file(value)

  send_file("public/downloads/test/" +  value  +".pdf", :filename => value + ".pdf", :type => "application/pdf", :diposition => "inline")

end

但是当我调用我的测试方法时,只下载了我的数组的最后一个元素。控制台打印以下内容:

 Sent file public/downloads/shapefiles/test1.pdf (0.1ms)
 Sent file public/downloads/shapefiles/test2.pdf (0.1ms)
 Sent file public/downloads/shapefiles/test3.pdf (0.1ms)
 Completed 200 OK in 2ms (ActiveRecord: 0.0ms)

但是我的浏览器只下载了最后一个文件,在本例中是test3.pdf

愿有人知道为什么会这样吗?

ruby-on-rails sendfile
1个回答
2
投票

send_file实际上指示服务器发送文件,而不是自己发送。例如,如果使用了正确配置的nginx - rails将只发出X-Accel-Redirect头,所有其他文件处理将由nginx完成。其他设置行为通常相同(但没有反向代理文件上传仍会阻止一些ruby进程/线程)

这就是为什么只发送最后一个文件。

因此,要下载多个文件,应将它们打包成一个。您可以使用类似于X-accel-redirect的技术,使用nginx_mod_zip动态创建zip

© www.soinside.com 2019 - 2024. All rights reserved.