Rubyzip下载附件没有创建存档
我使用rubyzip
与rails 4
我试图做一个自定义的方法来下载提交表中的所有附件,而不用phisically创建zip文件。Rubyzip下载附件没有创建存档
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?
这是使我的代码工作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
更改代码:
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
。
感谢此。我虽然仍然得到访问错误'Permission denied @ sys_fail2 - ' –
你应该检查文件夹,并查看文件是否保存在'tmp'目录中。 –
我把它改成了'/ tmp/archive.zip'。该文件夹在那里,但我得到一个未发现的错误 - >没有这样的文件或目录@ rb_sysopen - /tmp/archive.zip20161124-11560-1wprn6o。我不知道我在这里做错了什么 –
这可能帮助:http://*.com/questions/2405921/how-can-i-generate-zip- file-without-saving-to-the-disk-with-ruby – eugen
制作一个tmp文件并发送它,有什么问题? –
我不太清楚如何做到这一点 –