如何在Ruby on Rails中解压缩文件? [英] How to unzip a file in Ruby on Rails?

查看:196
本文介绍了如何在Ruby on Rails中解压缩文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby on Rails中将文件上传到服务器



通常,它是一个文本文件,并将其作为文件字段保存在模型中在提交ActiveRecord与其他字段,如标题的提交..等。



但是,用户还可以提交一个zip文件。在这种情况下,zipfile应该解压缩,对于zip中的每个文件,应该使用相同的文本字段,但是当前文件创建一个新的提交。



我如何完成这个?



我查看了网上的解压缩示例,但大多数使用目录将文件解压缩到。我不知道如果我需要这样的,如在SubmissionsController的当前创建方法中,接收到一个文件对象,并且在调用提交保存方法时,会自动生成保存文件的路径。所以我想,也许我应该解压zip文件在内存中获得一个文件对象数组,然后创建一个新的提交与每个文件对象,但相同的字段,然后让ActiveRecord生成文件路径,当它们保存到数据库。
我可能在这里错了,因为我是Rails和Ruby的新手。

解决方案

请使用 ruby​​zip宝石。具体来说,这部分是: https://github.com/rubyzip/rubyzip /blob/master/lib/zip/filesystem.rb



它在内存中创建一个人工文件系统,镜像zip文件的内容。这里是一个基于文档示例的示例:



Rubyzip界面已更改!没有必要要求zip / zip和删除类名中的Zip前缀。

  require 'zip'

Zip :: File.open(my.zip)do | zipfile |
zipfile.each do | file |
#用文件
结束
结束

在你的的例子中,只是放置了上传的临时文件的名称,其中 my.zip 在这个例子中,你可以循环遍历内容,并对它们进行常规的操作。 >

I'm uploading a file to the server in Ruby on Rails

Normally, it's a text file and I save it in the model as a 'file' field in a Submission ActiveRecord with other fields such as title of submission.. etc.

However, the user can also submit a zip file. In this case the zipfile should unzipped and for each file in the zip a new Submission should be created with the same text fields, but current file.

How can I accomplish this?

I looked at unzip examples on the net, but most use a directory to unzip the files to. I'm not sure if I need that as in the current create method of SubmissionsController, a file object is received and I presume the path to save the file to is automatically generated when the Submission save method is called. So I was thinking that maybe I should unzip the zipfile in memory to get an array of file objects and then create a new Submission with each file object but same fields and then let ActiveRecord generate the file paths for each one when it saves them to the database. I might be wrong here, because I'm kind of new to Rails and Ruby.

解决方案

I'd use the rubyzip gem. Specifically this part: https://github.com/rubyzip/rubyzip/blob/master/lib/zip/filesystem.rb

It creates an artificial file system in memory mirroring the contents of the zip file. Here's an example based of the example from the docs:

Rubyzip interface changed!!! No need to do require "zip/zip" and Zip prefix in class names removed.

require 'zip'

Zip::File.open("my.zip") do |zipfile|
  zipfile.each do |file|
    # do something with file
  end
end

In your case, just put the name of the uploaded tempfile where my.zip is in the example, and you can loop through the contents and do your regular operations on them.

这篇关于如何在Ruby on Rails中解压缩文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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