1

Trying to create a zip file containing many pictures, my code is as follows:

       compressed_filestream = Zip::OutputStream.write_buffer do |zos|
      @pictures.each do |p|
        image_url = p.picturefile.url(:original)
        zos.put_next_entry p.picturefile_file_name
        zos.print(URI.parse(image_url))    
      end
    end
    compressed_filestream.rewind
    send_data compressed_filestream.read, filename: "pictures.zip"

This creates a pictures.zip file, but it only contains the text-url of each image instead of the actual image...

hso
  • 345
  • 3
  • 19

2 Answers2

4

Right now you are just passing the URL of the image to the file. What you need to do is pass in the row contents to it.

compressed_filestream = Zip::OutputStream.write_buffer do |zos|
  @pictures.each do |p|
    zos.put_next_entry p.picturefile_file_name
    zos.print(Paperclip.io_adapters.for(p.picturefile).read)    
  end
end
compressed_filestream.rewind
send_data compressed_filestream.read, filename: "pictures.zip"
coderhs
  • 4,357
  • 1
  • 16
  • 25
0

Adding to the solution provided above,

In case you want to save it locally and provide path to download this zip file at later point or through API

compressed_filestream = Zip::OutputStream.write_buffer do |zos|
  @pictures.each do |pic|
    zos.put_next_entry pic.upload_file_name
    zos.write(Paperclip.io_adapters.for(pic.upload.url).read)
  end
end
File.open("#{Rails.root}/public/system/#{file_name}", 'wb') { |f| f.write(compressed_filestream.string) }
Abhinay
  • 1,796
  • 4
  • 28
  • 52