首页 > 解决方案 > 如何使用 ruby​​zip 将 zip 存档中的文件附加到 ActiveStorage 对象 Rails 5

问题描述

我有一个带有一个使用 ActiveStorage 的附件的模型:

class ProofreadDocument < ApplicationRecord

  has_one_attached :file

end

我正在执行一项将文件附加到校对文档的 rake 任务。这些文件被压缩到一个 zip 存档中。

我知道我可以通过阅读 ActiveStorage 文档来附加以下文件:

@proofread_document.file.attach(io: File.open('/path/to/file'), filename: 'file.pdf')

我的 rake 任务中有以下内容:

    Zip::File.open(args.path_to_directory) do |zipfile|
          zipfile.each do |file|
            proofread_document = ProofreadDocument.new()
            proofread_document.file.attach(io: file.get_input_stream.read, filename: file.name)
            proofread_document.save
          end
     end

这会产生以下错误:

NoMethodError: undefined method `read' for #<String:0x007f8d894d95e0>

我需要一次阅读每个文件的内容,以将它们附加到 proofread_document 实例。我怎样才能做到这一点?

标签: rubyruby-on-rails-5rubyzip

解决方案


通过将输入流包装在 StringIO 对象中,我能够成功,如下所示:

self.file.attach(io: StringIO.new(zip_entry.get_input_stream.read), filename: zip_entry.name, content_type: MS_WORD_CONTENT_TYPE)

推荐阅读