Rails how to view a txt file?

2020-07-30 03:19发布

问题:

How is it possiable to open an view a txt file with rails?

Example I have test.txt:

Test test test test

Then I have my test.html.erb:

Here I want to view test.txt

回答1:

You can either render an arbitrary file or use send_file: 3.1 or < 3.1



回答2:

Another possibility is:

Here is the test.txt file: <%= File.read("test.txt") %>


回答3:

In some cases (when the file is not small and loading it is connected with a delay), I prefer to load the page content and then to use jQuery ajax request to load the file content.

For example, let's say I have a model with file path attribute. In the view layout I am doing something like this:

<pre data-source=" <%= (@file.path) %>"></pre>

Then in the corresponding js file I am loading the context like this:

$(document).ready ->
  $.ajax(
    url: $("pre").data("source")
    context: document.body
  ).done (response) ->
    $("pre").html response
    return
  return

Of course you can check the jQuery ajax documentation for more options. For example, you can render the pre tag with loading like this:

<pre data-source=" <%= (@file.path) %>"><div class="loading"></pre>

or use other jQuery animations as well.



回答4:

Here is the test.txt file:

<%= File.read(File.join(Rails.root, 'your_folder','your_folder','test.txt'))%>