I'm wondering if it's possible to do this in Rails:
我想知道是否可以在Rails中执行此操作:
Have a link on the webpage. When the user clicks on the link, the controller generates a file dynamically (say, a text file that contains a single random number between 1 and 10), and the file is downloaded onto the user's computer. The file might be temporarily stored on the server, but it shouldn't be permanently there.
在网页上有一个链接。当用户点击链接时,控制器动态生成文件(例如,包含1到10之间的单个随机数的文本文件),并将文件下载到用户的计算机上。该文件可能暂时存储在服务器上,但不应永久存储在服务器上。
2 个解决方案
#1
7
Use send_data
in the controller:
在控制器中使用send_data:
send_data("4", :filename => "my_awesome_file")
If you already have the file on the server, you can use send_file
instead
如果您已在服务器上拥有该文件,则可以使用send_file
send_file(filepath, :filename => "my_awesome_file")
http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_data
http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_data
#2
3
Yes, it's possible. This is what I have in one of my apps:
是的,这是可能的。这就是我在其中一个应用中所拥有的:
class DownloadsController < ApplicationController
def download
# ...
send_file CSVConstructor::Constructor.new(...).to_zip
end
end
The download
action takes params submitted from a form and sends them to a custom class that generates a few files, packages them as a zip, and returns the file path. You'll have to figure out the best way to generate files for your own app, but I would recommend something similar - branching the functionality into a separate class helps keep your controller light.
下载操作从表单提交params并将它们发送到生成一些文件的自定义类,将它们打包为zip,然后返回文件路径。你必须找出为你自己的应用程序生成文件的最佳方法,但我会推荐类似的东西 - 将功能分成一个单独的类有助于保持你的控制器轻。
#1
7
Use send_data
in the controller:
在控制器中使用send_data:
send_data("4", :filename => "my_awesome_file")
If you already have the file on the server, you can use send_file
instead
如果您已在服务器上拥有该文件,则可以使用send_file
send_file(filepath, :filename => "my_awesome_file")
http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_data
http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_data
#2
3
Yes, it's possible. This is what I have in one of my apps:
是的,这是可能的。这就是我在其中一个应用中所拥有的:
class DownloadsController < ApplicationController
def download
# ...
send_file CSVConstructor::Constructor.new(...).to_zip
end
end
The download
action takes params submitted from a form and sends them to a custom class that generates a few files, packages them as a zip, and returns the file path. You'll have to figure out the best way to generate files for your own app, but I would recommend something similar - branching the functionality into a separate class helps keep your controller light.
下载操作从表单提交params并将它们发送到生成一些文件的自定义类,将它们打包为zip,然后返回文件路径。你必须找出为你自己的应用程序生成文件的最佳方法,但我会推荐类似的东西 - 将功能分成一个单独的类有助于保持你的控制器轻。