Awea
Awea

Reputation: 3173

Download Paperclip files as ZIP

Actually I'm doing something like this :

project          = Project.find(params[:id])  
attachments_list = project.attachments.where{attach_file_size > 0}
assets_list      = project.assets.where{image_file_size > 0}
#Person.where{(name =~ 'Ernie%') & (salary < 50000) | (name =~ 'Joe%') & (salary > 100000)}
file_name  = project.title.downcase.gsub(' ', '_destroy')
file_name  = "#{file_name}.zip"

temp_file  = Tempfile.new("#{file_name}-#{current_user.id}")
Zip::ZipOutputStream.open(temp_file.path) do |zos|
  attachments_list.each do |file|
    zos.put_next_entry(file.title)
    zos.print IO.read(file.attach.path)
  end
  assets_list.each do |file|
    zos.put_next_entry(file.title)
    zos.print IO.read("#{file.image.path}")
  end
end

send_file temp_file.path, :type => 'application/zip',
                          :disposition => 'attachment',
                          :filename => file_name
temp_file.close

It's work but the extension is missing on the received files, any idea ?

Upvotes: 5

Views: 1900

Answers (3)

octopushugs
octopushugs

Reputation: 157

I did something similar, but needed to grab files from S3 instead of the local system. My files weren't large, so I decided to just load them into memory. So instead of this:

zos.print IO.read(file.attach.path)

I added a require "open-uri" and then did this:

zos.print open(asset.data.url) {|f| f.read}

Where asset is a paperclip object.

Upvotes: 1

Awea
Awea

Reputation: 3173

I finally make a method inside the concerned model to return the file name with the extension

def title_with_ext
    "#{self.title}#{File.extname(self.image.path)}"
end

Upvotes: 2

Donavan White
Donavan White

Reputation: 1126

Just change :filename => file_name to :filename => file_name.zip

:type only specifies the application that will use the file, but not the extension to the filename

Upvotes: 0

Related Questions