Rubyzip 下载附件而不创建存档

Rubyzip download attachments without creating the archive

我将 rubyziprails 4 一起使用,并且我正在尝试创建一个自定义方法来下载提交 table 中的所有附件,而无需物理创建 zip 文件。

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

如何正确设置文件变量。文档说那是存档名称,但我不想创建该物理存档。也许只是一个 tmp?

更改您的代码:

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_file 而不是 send_data

这是使我的代码 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