1

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 ?

4

2 回答 2

1

更改您的代码:

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

你应该使用send_filenot send_data

于 2016-11-24T11:16:43.843 回答
0

这是使我的代码 100% 正常工作的正确语法:

# 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
于 2016-11-28T13:37:52.980 回答