Rails - 在每个循环中使用 send_file 同时下载多个文件
Rails - Download multiple files at same time using send_file in a each loop
我想循环下载数组中每个值的文件。
我的 class 中有两种方法:
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
。
send_file
实际上是指示服务器发送一个文件,而不是自己发送。例如,如果使用正确配置的 nginx - rails 将仅发出 X-Accel-Redirect
header,所有其他文件处理将由 nginx 完成。其他设置的行为大致相同(但没有反向代理文件上传仍然会阻止一些 ruby process/thread)
这就是为什么只发送最后一个文件的原因。
所以要下载多个文件,他们应该打包成一个。您可以使用 nginx_mod_zip 使用类似于 X-accel-redirect
的技术动态创建 zip
我想循环下载数组中每个值的文件。
我的 class 中有两种方法:
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
。
send_file
实际上是指示服务器发送一个文件,而不是自己发送。例如,如果使用正确配置的 nginx - rails 将仅发出 X-Accel-Redirect
header,所有其他文件处理将由 nginx 完成。其他设置的行为大致相同(但没有反向代理文件上传仍然会阻止一些 ruby process/thread)
这就是为什么只发送最后一个文件的原因。
所以要下载多个文件,他们应该打包成一个。您可以使用 nginx_mod_zip 使用类似于 X-accel-redirect
的技术动态创建 zip