【问题标题】:Download file in service object with ActiveStorage使用 ActiveStorage 下载服务对象中的文件
【发布时间】:2020-04-20 13:04:18
【问题描述】:

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

当我仍然使用回形针时,我做了这样的事情:

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 做类似的事情?

【问题讨论】:

    标签: ruby-on-rails rails-activestorage


    【解决方案1】:

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

    将 blob 下载到磁盘上的临时文件。生成临时文件。

    鉴于指南中的这个例子:

    class User < ApplicationRecord
      has_one_attached :avatar
    end
    

    你可以这样做:

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

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

    见:

    【讨论】:

    • 如果你真的想获取附件的 url,你可以通过 blob 上的 #url 方法而不是 helper 方法来获取它。
    • This:# do something with the file -> 如何将文件下载到 Rails 应用程序中的“tmp”文件夹?
    • 使用user.avatar.open(tmpdir: Rails.root.join('tmp')) do ...。但由于它是一个临时文件,它会在块的末尾自动关闭并取消链接。如果您想让文件永久使用ObjectSpace.undefine_finalizer(tempfile) 或使用Blob#download 代替将下载流式传输到常规文件/IO 实例。
    猜你喜欢
    • 2019-01-30
    • 2010-11-25
    • 2016-01-21
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多