Rubyzip下载附件而无需创建存档



我正在使用rails 4使用rubyzip,我正在尝试制作一种自定义方法,以下载提交表中的所有附件,而无需呈现phise the 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

如何正确设置文件var。文档说那是存档名称,但我不想创建该物理存档。也许是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

相关内容

  • 没有找到相关文章

最新更新