创建多个csv文件并使用rails在一个zip归档文件中全部下载 [英] Creating multiple csv-files and download all in one zip-archive using rails

查看:148
本文介绍了创建多个csv文件并使用rails在一个zip归档文件中全部下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来创建多个csv文件,并将其作为一个zip归档文件下载到我的rails应用程序中的一个请求中。

I am looking for a way to create multiple csv files and download them as one zip archive within one request in my rails application.

我使用的是建立归档文件rubyzip gem-仅下载rails内置函数send_data。我的问题是rubyzip的添加功能需要一个路径名才能从中加载文件。但是没有路径,因为我的csv文件是在同一请求中创建的。

To build the archive I use rubyzip gem - to download it just the rails built-in function send_data. The problem I have is that rubyzip's add-function requires a pathname to load files from. But there is no path as my csv files are created within the same request.

某些代码:

# controller action to download zip
def download_zip
  zip = @company.download_all
  send_data zip, filename: "abc.zip", type: 'application/zip'
end

# method to create zip
def download_all
  Zip::File.open('def.zip', Zip::File::CREATE) do |zipfile|
    self.users.each do |user|
      #some magic to combine zipfile.add() and user.to_csv
    end
  end
end

# method to create csv
def to_csv
  CSV.generate do |csv|
    #build awesome csv
  end
end

是否有临时保存我的csv文件的方法,可以将路径名传递给zipfile.add()?

Is there a way to save my csv files temporarely at some directory, that I can pass a pathname to zipfile.add()?

大家周末愉快,编码愉快!

Nice weekend everybody and happy coding!

推荐答案

将您的CSV输出写入一个临时文件并在其上调用zipfile.add(),但有一个更干净的解决方案:

You could either write your CSV output into a temporary file and call zipfile.add() on that, but there is a cleaner solution:

zipfile.get_output_stream("#{user.name}.csv") { |f| f.puts(user.to_csv) }

请参见 http://rdoc.info/github/rubyzip/rubyzip/master/Zip/File#get_output_stream-instance_method 有关get_output_stream的更多详细信息-您还可以传递其他参数来指定要创建的文件的属性。

See http://rdoc.info/github/rubyzip/rubyzip/master/Zip/File#get_output_stream-instance_method for more details on get_output_stream - you can also pass additional parameters to specify attributes for the file to be created.

这篇关于创建多个csv文件并使用rails在一个zip归档文件中全部下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆