ruby-on-railsruby-on-rails-7

Rails 7: Downloadable files in folders outside project folder


I am working on a project in which users can create PDF files and then download them. Currently, I am creating these PDFs inside "public/" folder in the project. But, I want to change the path to a folder outside the project folder, but on the same server.

There is no problem in saving the files in this external folder, but, how do I allow users to download the files in the front-end. Is there a way to make files in external folder downloadable.

Basically I want this external folder to work same as "public" folder.

In Phoenix, there is a way to do this by adding a one line configuration that links external folder to project url. Is there something similar in Rails?

This is my first project in rails. So kind of lost.


Solution

  • It turns out that serving files from outside the root folder isn't much different from serving them from "public" folder. Here is what I did:

    1. I created a folder to store the generated PDFs outside the project's root folder. And in my "environments/.rb" file, I added following configuration:

    config.pdf_directory = "/home/deploy/pdf"

    1. In the controller where I am generating PDF, I used "send_file" to return the generated file. (Since the request is already in the Rails stack, I guess it is okay to serve file like this here)
    send_file(
        "#{Rails.configuration.pdf_directory}/#{pdf_file_name}",
        filename: "#{pdf_file_name}",
        type: "application/pdf"
    )
    
    1. In my index page, where I have a download link for users to download the file in the future, I have used Apache server configurations to server them from that folder directly
    Alias "/pdfs" "/home/deploy/pdf"
    <Directory "/home/deploy/pdf">
        Require all granted
    </Directory>
    

    I can now access/serve the generated files using the URL similar to: https://example.com/pdfs/file1.pdf