如何在Rails应用程序中发送动态生成的文件 [英] How to send a dynamically generated file in a rails app

查看:88
本文介绍了如何在Rails应用程序中发送动态生成的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Rails应用程序中提供动态生成的文件,因此当用户单击特定链接时,将使用send_data生成文件并将其发送到客户端。



该文件不打算重用:是一个短文本文件,并且重新生成应该是真正便宜的,因为它不会被大量下载。但是,如果有必要或方便的话,我可以将其存储在数据库中,这样只会生成一次。



首先,我想在内存中生成文件并将其发送在控制器中。我正在尝试归档以下内容:

  def DownloadsController< ApplicationController 
def project_file
project = Project.find(params [:id])
send_data project.generate_really_simply_text_file_report
end
end

但是我不知道如何在内存中生成流,因此在文件系统中没有文件创建。



另一种选择是在rails app tmp目录中生成一个具有随机名称的文件,然后从ther发送该文件,但是该文件将保留在该文件中,这是我不希望发生的事情



编辑:如果我没记错的话,send_file会阻止请愿书,直到文件被发送出去,这样才可以正常工作。

还有其他建议或意见吗?



预先感谢

解决方案

如果您所描述的是一个简单的问题,则可以使用类似的简单解决方案。只是不要忘记:filename 选项,否则文件将被命名为 project_file。

  def project_file 
project = Project.find(params [:id])
send_data project.generate_really_simply_text_file_report,:filename => #{project.name} .txt
结尾

编辑:



您的 project#generate_really_simply_text_file_report 应该返回二进制数据,文件路径或原始数据

  def下载
content =块状培根\牛尼斯
send_data内容,:filename => bacon.txt
结束


I'm trying to serve a dynamically generated files in a rails app, so when the user clicks a specific link, the file is generated and sent to the client using send_data.

The file is not intended to be reused: is a short text file and regenerating should be really inexpensive as it won't be donwloaded that much; but if it is necessary or convenient I could store it in the database so is only generated once.

First, I would like to generate the file in memory, and send it in the controller. I'm trying to archive something like this:

def DownloadsController < ApplicationController
  def project_file
    project = Project.find(params[:id])
    send_data project.generate_really_simply_text_file_report
  end
end

But i don't know how to generate a stream in memory, so no file is created in the file system.

Another option would be generating the file with a random name in the rails app tmp directory and send it from ther, but then the file will be kept there, which is something I would prefer not to happen.

Edit: If I'm not mistaken, send_file blocks the petition until the file is sent, so it could work...

Any other advices or opinions?

Thanks in advance

解决方案

If it's a simple problem as you describe it, a simple solution like that will do. Just don't forget the :filename option, otherwise the file will be named as "project_file".

  def project_file
    project = Project.find(params[:id])
    send_data project.generate_really_simply_text_file_report, :filename => "#{project.name}.txt"
  end

Edit:

your project#generate_really_simply_text_file_report should return either the binary data, the path for the file or a raw String.

  def download
    content = "chunky bacon\r\nis awesome"
    send_data content,  :filename => "bacon.txt" 
  end

这篇关于如何在Rails应用程序中发送动态生成的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆