Active Storage 預覽
某些非圖片的二進位大物件可以預覽:即,它們可以顯示為圖片。影片二進位大物件可以透過擷取其第一個畫格進行預覽,PDF 二進位大物件可以透過擷取其第一頁進行預覽。
預覽器從二進位大物件中擷取預覽影像。Active Storage 提供影片和 PDF 預覽器。ActiveStorage::Previewer::VideoPreviewer
用於影片,而 ActiveStorage::Previewer::PopplerPDFPreviewer
和 ActiveStorage::Previewer::MuPDFPreviewer
用於 PDF。透過繼承 ActiveStorage::Previewer
和實作必要的函式,建置自訂預覽器。查看 ActiveStorage::Previewer
文件以取得預覽器所需條件的詳細資訊。
為了選擇二進位大物件的預覽器,Active Storage 會依序呼叫每個註冊預覽器的 accept?
。對於 accept?
在提供二進位大物件時傳回 true 的第一個預覽器,它會使用它。在 Rails 應用程式中,透過在初始設定檔中操作 Rails.application.config.active_storage.previewers
來新增或移除預覽器
Rails.application.config.active_storage.previewers
# => [ ActiveStorage::Previewer::PopplerPDFPreviewer, ActiveStorage::Previewer::MuPDFPreviewer, ActiveStorage::Previewer::VideoPreviewer ]
# Add a custom previewer for Microsoft Office documents:
Rails.application.config.active_storage.previewers << DOCXPreviewer
# => [ ActiveStorage::Previewer::PopplerPDFPreviewer, ActiveStorage::Previewer::MuPDFPreviewer, ActiveStorage::Previewer::VideoPreviewer, DOCXPreviewer ]
在 Rails 應用程式之外,請修改 ActiveStorage.previewers
。
內建預覽器仰賴於協力廠商的系統函式庫。具體而言,內建影片預覽器需要 FFmpeg。提供兩個 PDF 預覽器:一種需要 Poppler,另一種需要 muPDF(版本 1.8 或更新版本)。要預覽 PDF,請安裝 Poppler 或 muPDF。
Rails 未提供這些函式庫。您必須自行安裝它們才能使用內建預覽器。在您安裝和使用協力廠商軟體之前,請確定您了解這樣做的授權意涵。
屬性
[R] | blob | |
[R] | variation |
類別公開函式
new(blob, variation_or_variation_key) 連結
來源: 顯示 | 在 GitHub 上
# File activestorage/app/models/active_storage/preview.rb, line 42 def initialize(blob, variation_or_variation_key) @blob, @variation = blob, ActiveStorage::Variation.wrap(variation_or_variation_key) end
執行個體公開函式
download(&block) 連結
下載與此預覽的變體關聯的檔案。如果未提供區塊,整個檔案會讀取到記憶體中並傳回。這會讓非常大的檔案使用大量的 RAM。如果提供區塊,則會串流下載並以區塊為單位提供。如果尚未處理預覽,就會 raise ActiveStorage::Preview::UnprocessedError
。
來源: 顯示 | 在 GitHub 上
# File activestorage/app/models/active_storage/preview.rb, line 90 def download(&block) if processed? presentation.download(&block) else raise UnprocessedError end end
image() 連結
傳回二進位大物件已附加的預覽影像。
來源: 顯示 | 在 GitHub 上
# File activestorage/app/models/active_storage/preview.rb, line 59 def image blob.preview_image end
key() 連結
傳回 blob 及變異的組合金鑰來共同識別特定變異。
來源:顯示 | 在 GitHub 上
# File activestorage/app/models/active_storage/preview.rb, line 77 def key if processed? presentation.key else raise UnprocessedError end end
processed() 連結
處理預覽(如果尚未處理)。傳回接收的 ActiveStorage::Preview
實例以利後續使用。
blob.preview(resize_to_limit: [100, 100]).processed.url
處理預覽會由其 blob 產生影像檔,並將預覽影像附加到 blob。由於預覽影像會與 blob 一起儲存,因此只會產生一次。
來源:顯示 | 在 GitHub 上
# File activestorage/app/models/active_storage/preview.rb, line 52 def processed process unless processed? variant.processed if variant? self end
url(**options) 連結
傳回服務上預覽變異的 URL。如果尚未處理預覽,會引發 ActiveStorage::Preview::UnprocessedError
。
這個方法會同步處理預覽影像的變異,請勿在檢視中呼叫它。相反地,請產生一個會重新導向到此方法傳回 URL 的穩定 URL。
來源:顯示 | 在 GitHub 上
# File activestorage/app/models/active_storage/preview.rb, line 68 def url(**options) if processed? presentation.url(**options) else raise UnprocessedError end end