Download an active Storage attachment to disc

耗尽温柔 提交于 2020-01-24 02:50:08

问题


The guide says that I can save an attachment to disc to run a process on it like this:

message.video.open do |file|
  system '/path/to/virus/scanner', file.path
  # ...
end

My model has an attachment defined as:

has_one_attached :zip

And then in the model I have defined:

def process_zip      
  zip.open do |file|
    # process the zip file
  end
end

However I am getting an error :

private method `open' called

on the zip.open call.

How can I save the zip locally for processing?


回答1:


As an alternative in Rails 5.2 you can do this:

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

   Zip::File.open(zip_path) do |zip_file|  
       # process the zip file
       # ...
       puts "processing file #{zip_file}"
   end
end



回答2:


That’s an edge guide (note edgeguides.rubyonrails.org in the URL); it applies to the master branch of the rails/rails repository on GitHub. The latest changes in master haven’t been included in a released version of Rails yet.

You’re likely using Rails 5.2. Use edge Rails to take advantage of ActiveStorage::Blob#open:

gem "rails", github: "rails/rails"


来源:https://stackoverflow.com/questions/50529659/download-an-active-storage-attachment-to-disc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!