簡體   English   中英

顯示給定 Rails DB 中的文件內容

[英]Display file contents from the given Rails DB

我可以使用以下方式顯示特定文件的內容: <%= render file: "#{Rails.root}/filepath", layout: false %>但是,我需要動態訪問數據庫中的每個文件並獲取其文件路徑。

index.html.erb查看文件中,我link_to articles_path ,也就是這條路由article GET - /articles/:id(.:format) - articles#show 這意味着節目 URL 以 article/:id 結尾。 我可以通過使用實例變量@article.title 和@article.id 來顯示文件標題和ID。 此外,我可以使用<%= link_to "View File", @article.file%>獲取下載鏈接,這是在顯示視圖頁面中下載文件的示例鏈接(當我檢查頁面時) <a href="/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--045b71b4dec3d3bfe6cec88145761e50106c0922/test2.txt">View File</a> 但是,我不想下載文件,只是在網頁上顯示內容(文本)。 如何動態訪問文件路徑?

我曾嘗試使用@filename = params[:file].original_filename (在 article_controller 的 show 方法中),因為這個堆棧溢出問題: 如何在 rails contoller 中獲取上傳文件的文件名 我不認為它有效。

我也嘗試<%= cdata_section(File.read(@filename)) %> (在view/show.html.erb文件中),但我得到一個未定義的錯誤:nil:NilClass 的未定義方法'original_filename'

代碼:

#application_record.rb
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

#article.rb
class Article < ApplicationRecord
  has_one_attached :file
end

#articles_controller.rb
class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end
  
  def show
    @article = Article.find(params[:id])
  end
  
  def new
  end
  
  def create
    @article = Article.new(params.require(:article).permit(:title, :text, :file)) 
    @article.save

    redirect_to @article
  end
  
  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end
  
  def article_params
    params.require(:article).permit(:title, :text, :file)
  end
end

我相信這些文件被存儲在本地 Rails DB 中的活動存儲 blob 中。 這是我的config/storage.yml 我們將文件存儲在本地,因此文件位於我的應用程序根目錄下的存儲目錄中的層次結構中

#config/storage.yml
test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

通過鏈接呈現內容不是完整堆棧頁面的選項。 您必須使用 xhr 請求(ajax 請求)來獲取內容,或者鏈接到呈現文件內容的視圖。

假設你想保持簡單,那么,有幾件事要做。

命名是常規的,根據自己的喜好調整。

創建到您的視圖的路線:

#config/routes.rb
get '/filecontents/:id', to: "articles#read"

然后,創建一個動作來渲染視圖

#app/controllers/articles_controller.rb
def read
    @article = Article.find params[:id]
    path = method_to_get_your_path_from_article #this is your job
    @text = File.open(path).read # get the contents in a variable
end

現在,假設您的文件具有文本文件結構,您所要做的就是創建一個最小視圖:

#views/articles/read.html.erb
<pre><%= @text %></pre>

這應該會讓你繼續前進。 當然,你必須加強它。

哦,別忘了設置link_to來顯示你剛剛創建的路線

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM