RM64
RM64

Reputation: 69

Writing active storage output to tempfile

How do you write the output of the activestorage download to a tempfile.

Whenever I read it out afterwards, it just becomes an empty string.

This is the code I've tried:

@file_temp = Tempfile.new
@file_temp.binmode
@file_temp.write(model.activestorage_attribute.download)

Upvotes: 3

Views: 6023

Answers (2)

max
max

Reputation: 101891

You can also just call ActiveStorage::Blob#open instead of reinventing the wheel.

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

blob.open do |temp_file|
  # do something with file...
end
# file is automatically closed and unlinked

If you really want to do it yourself then the right way to do it is:

# Using `Tempfile.open with a block ensures that
# the file is closed and unlinked
Tempfile.open do |tempfile| 
  tempfile.binmode
  # steams the file as chunks instead of loading it 
  # all into memory
  model.activestorage_attribute.download do |chunk|
    tempfile.write(chunk)
  end
  tempfile.rewind
  # do something with tempfile
end

Upvotes: 6

kinduff
kinduff

Reputation: 142

The ActiveStorage::Blob#download will provide you with a blob that can be used to different operations from memory.

The Tempfile.new will create files which are IO objects and have a position pointer. When you write to a file, the position will advance.

You need to rewind to the position. Try the following:

@file_temp = Tempfile.new
@file_temp.binmode
@file_temp.write(model.activestorage_attribute.download)
@file_temp.rewind

Then you'll be able to read the data:

@file_temp.read
#=> "...\x8F\xFF\x00\x16G\xFE\xAE\x0F\xE5\x0E\xED..."

Upvotes: 4

Related Questions