2017-05-07 101 views
0

我试图创建一个函数,可以下载包含文件的zip文件。我跟着this tutorial,上面写着我的代码看起来应该像下面的,如果你想下载一个CSV(我翻译的评论):“创建zip文件时无法打开条目阅读,而其打开”

def exporter_zip 
    # CSV's header 
    csv = "Title;Content;Publishing date;File name;\n" 
    # Loop over articles saved in database 
    Article.all.each do |article| 
     # Creating the CSV with datas 
     csv += "#{article.title};#{article.content};#{article.publishing_date.strftime("%Y-%m-%d") if article.publishing_date };#{article.file_name}\n" 
    end 

    # Creating the zip file inside the folder 
    zip_tmp = File.new("#{Rails.root}/db/mon_fichier.zip", "w+") 

    # opening the file in writing mode 
    Zip::File.open(zip_tmp.path, Zip::File::CREATE) { 
     |zipfile| 

    # Inserting the csv variable's content inside the article.csv file, which is inserted into the zip file 

     zipfile.get_output_stream("articles.csv") { |f| f.puts csv } 
    } 

    # Sending the created file 
    send_file "#{Rails.root}/db/mon_fichier.zip" 
    end 

这里是我如何适应代码:

class DownloadController < ApplicationController 
    require 'zip' 

    def zip 
    # Creating zip file 
    zip_tmp = File.new("#{Rails.root}/public/zip-#{Time.now.strftime('%d-%m-%Y')}.zip", 'w+') 
    FileDetail.all.each do |fichier| 
     Zip::File.open(zip_tmp.path, Zip::File::CREATE) { |zipfile| 
     # fichier.filename => file.mp3 
     # fichier.path => path/to/file.mp3 
     zipfile.get_output_stream(fichier.filename, fichier.path) 
     } 
    end 

    send_file "#{Rails.root}/public/zip-#{Date.today.to_time}.zip" 
    end 
end 

然而,虽然我甚至不确定我是否正确地做到这一点,但我得到以下错误:cannot open entry for reading while its open for writing,针对以下行:Zip::File.open(zip_tmp.path, Zip::File::CREATE) { |zipfile|

任何人都可以告诉我发生了什么事吗?我从来没有这样做之前,所以我不知道哪里出了问题..

预先感谢您

回答

1
FileDetail.all.each do |fichier| 
    Zip::File.open(zip_tmp.path, Zip::File::CREATE) { |zipfile| 
    # fichier.filename => file.mp3 
    # fichier.path => path/to/file.mp3 
    zipfile.get_output_stream(fichier.filename, fichier.path) 
    } 
end 

这样做,这样会尝试为您FileDetail的每个成员的zip文件。您应该将其编码为仅打开并创建一次:

Zip::File.open(zip_tmp.path, Zip::File::CREATE) do |zipfile| 
    FileDetail.all.each do |fichier| 
    # fichier.filename => file.mp3 
    # fichier.path => path/to/file.mp3 
    zipfile.get_output_stream(fichier.filename, fichier.path) 
    end 
end 
+0

谢谢,我还必须将'get_output_stream'更改为'add',但它现在可用! – Jaeger