Vlad Balanescu
Vlad Balanescu

Reputation: 674

Rubyzip download attachments without creating the archive

I am using rubyzip with rails 4 and I am trying to make a custom method to download all the attachments in the submission table without phisically creating the zip file.

submissions_controller.rb

  def download
    @submissions = Submission.all

    file = "#{Rails.root}/tmp/archive.zip"

    Zip::ZipFile.open(file, Zip::ZipFile::CREATE) do |zipfile|
      @submissions.each do |filename|
       zipfile.add(file, filename.file.url(:original, false))
      end
    end
   zip_data = File.read(file)
   send_data(zip_data, :type => 'application/zip', :filename => "All submissions")
  end

How can I set the file var right. The documentation says that that is the archive name, but I do not want to create that physical archive. Maybe just as a tmp ?

Upvotes: 1

Views: 930

Answers (2)

Vlad Balanescu
Vlad Balanescu

Reputation: 674

This is the right syntax that made my code work 100% fine:

# Download zip file of all submission
  def download
    @submissions = Submission.all

    archiveFolder = Rails.root.join('tmp/archive.zip') #Location to save the zip

    # Delte .zip folder if it's already there
    FileUtils.rm_rf(archiveFolder)

    # Open the zipfile
    Zip::ZipFile.open(archiveFolder, Zip::ZipFile::CREATE) do |zipfile|
      @submissions.each do |filename|
        zipfile.add(filename.file_file_name, 'public/files/submissions/files/' + filename.id.to_s + '/original/' + filename.file_file_name)
      end
    end

    # Send the archive as an attachment
    send_file(archiveFolder, :type => 'application/zip', :filename => '2016 Submissions.zip', :disposition => 'attachment')
  end

Upvotes: 0

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

Change your code:

def download
  @submissions = Submission.all

  file = "#{Rails.root}/tmp/archive.zip"

  Zip::ZipFile.open(file, Zip::ZipFile::CREATE) do |zipfile|
    @submissions.each do |filename|
      zipfile.add(file, filename.file.url(:original, false))
    end
  end
  send_file(file, :type => 'application/zip', :filename => "All submissions")
end

You should use send_file not send_data.

Upvotes: 1

Related Questions