How to send dynamically generated file in rails application

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

The file is not intended for reuse: it is a short text file, and regeneration should be really inexpensive, since it will not be heavily loaded; but if it is necessary or convenient, I can save it in the database, so that it is generated only once.

First, I would like to generate a file in memory and send it to the controller. I am 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 do not know how to create a stream in memory, so a file is not created in the file system.

Another option is to generate a file with a random name in the rails app tmp directory and send it with ther, but then the file will be stored there, which I would rather not do.

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

Any other tips or opinions?

Thanks in advance

+4
source share
1 answer

If this is a simple problem, as you described it, this is a simple solution. Just don't forget the :filename parameter, 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 binary data, file path or raw string.

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

Source: https://habr.com/ru/post/1300282/


All Articles