获取磁盘上ActiveStorage文件的路径

时间:2018-05-14 22:47:06

标签: ruby-on-rails ruby rails-activestorage

我需要获取正在使用ActiveStorage的磁盘上的文件的路径。该文件存储在本地。

当我使用paperclip时,我在附件上使用path方法返回完整路径。

示例:

user.avatar.path

在查看 Active Storage Docs时,看起来rails_blob_path可以解决问题。在查看它返回的内容之后,它没有提供文档的路径。因此,它返回此错误:

  

没有这样的文件或目录@ rb_sysopen -

背景

我需要文档的路径,因为我使用combine_pdf gem来将多个pdf合并为一个pdf。

对于回形针实现,我遍历所选pdf附件的full_path并将load组合成pdf组合:

attachment_paths.each {|att_path| report << CombinePDF.load(att_path)}

4 个答案:

答案 0 :(得分:16)

只需使用:

ActiveStorage::Blob.service.send(:path_for, user.avatar.key)

您可以在模型上执行以下操作:

class User < ApplicationRecord
  has_one_attached :avatar

  def avatar_on_disk
    ActiveStorage::Blob.service.send(:path_for, avatar.key)
  end
end

答案 1 :(得分:6)

感谢评论中@muistooshort的帮助,在查看Active Storage Code后,这有效:

active_storage_disk_service = ActiveStorage::Service::DiskService.new(root: Rails.root.to_s + '/storage/')
active_storage_disk_service.send(:path_for, user.avatar.blob.key)
  # => returns full path to the document stored locally on disk

这个解决方案对我来说有点不舒服。我很想听听其他解决方案。这对我有用。

答案 2 :(得分:4)

我不确定为什么其他所有答案都使用send(:url_for, key)。我使用的是 Rails 5.2.2 ,并且url_for是一种公共方法,因此,最好避免使用send或直接调用path_for

class User < ApplicationRecord
  has_one_attached :avatar

  def avatar_path
    ActiveStorage::Blob.service.path_for(avatar.key)
  end
end

值得注意的是,您可以在视图中执行以下操作:

<p>
  <%= image_tag url_for(@user.avatar) %>
  <br>
  <%= link_to 'View', polymorphic_url(@user.avatar) %>
  <br>
  Stored at <%= @user.image_path %>
  <br>
  <%= link_to 'Download', rails_blob_path(@user.avatar, disposition: :attachment) %>
  <br>
  <%= f.file_field :avatar %>
</p>

答案 3 :(得分:3)

您可以将附件下载到本地目录,然后进行处理。

假设您的模型中有:

has_one_attached :pdf_attachment

您可以定义:

def process_attachment      
   # Download the attached file in temp dir
   pdf_attachment_path = "#{Dir.tmpdir}/#{pdf_attachment.filename}"
   File.open(pdf_attachment_path, 'wb') do |file|
       file.write(pdf_attachment.download)
   end   

   # process the downloaded file
   # ...
end