使用 ActiveStorage 在服务对象中下载文件

Download file in service object with ActiveStorage

用户上传了一个文档,该文档通过 ActiveStorage 存储在 Azure 中。下一步是后端处理这个,因此我有一个服务对象来做这个。因此,我需要将文件从 Azure 下载到 Rails 应用程序中的 tmp 文件夹。如何下载文件?我不能使用 rails_blob_url 因为它在服务对象中不可用,仅在控制器和视图中可用。

当我还在使用 Paperclip 时,我做了这样的事情:

require 'open-uri'
file = Rails.root.join('tmp', user.attachment_file_name)
name = user.attachment_file_name
download = open(user.attachment.url)
download_result = IO.copy_stream(download, file)

如何使用 ActiveStorage 做类似的事情?

您可以使用 ActiveStorage::Blob#open:

Downloads the blob to a tempfile on disk. Yields the tempfile.

给出指南中的这个例子:

class User < ApplicationRecord
  has_one_attached :avatar
end

您可以使用:

user.avatar.open do |tempfile|
  # do something with the file
end

如果是 has_many_attached 你当然需要遍历附件。

参见: