我正在使用rubyzip
和rails 4
,我正在尝试制作一个自定义方法来下载提交表中的所有附件,而不是在创建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 right。文档说这是存档名称,但我不想创建该物理存档。也许就像一个tmp?
答案 0 :(得分: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_file
而不是send_data
。
答案 1 :(得分: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