Creating a file dynamically and downloading to a user computer

I am wondering if this can be done in Rails:

You have a link on a web page. When the user clicks on the link, the controller dynamically generates a file (say, a text file containing one random number from 1 to 10), and the file is downloaded to the user's computer. A file may be temporarily stored on the server, but it should not be permanently there.

+4
source share
2 answers

Use send_data in the controller:

 send_data("4", :filename => "my_awesome_file") 

If you already have a file on the server, you can use send_file instead

 send_file(filepath, :filename => "my_awesome_file") 

http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_data

+6
source

Yes it is possible. This is what I have in one of my applications:

 class DownloadsController < ApplicationController def download # ... send_file CSVConstructor::Constructor.new(...).to_zip end end 

The download action accepts the parameters passed from the form and sends them to a user class that generates several files, packs them as zip and returns the path to the file. You will need to find the best way to generate files for your own application, but I would recommend something similar - branching functionality into a separate class helps keep your controller light.

+3
source

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


All Articles