获取磁盘上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)}
只需使用:
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
您可以将附件下载到本地目录,然后进行处理。
假设你的模型中有:
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
感谢@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
这个解决方案对我来说有点不舒服。 我很想听听其他解决方案。 这对我有用。
- 使用Paperclip和Rails,Google Cloud Storage请求速度很慢
- jQuery的event.stopPropagation()导致Rails出现问题:remote => true