1
我有一个需求,在使用Base64编码对zip文件进行编码后,将zip文件发送到ROR应用程序。我应该解码它,将它保存为一个zip文件并解压缩并执行一些操作。他们通过POST方法发送zip文件编码数据作为参数zip
。这里是我在代码中所做的。Base64编码的字符串到文件(Ruby on Rails)
require 'rubygems'
require 'zip/zip'
require 'base64'
def get_pdf
encoded_data = Base64.decode64(params[:zip])
File.open("#{RAILS_ROOT}/zip_archive/zip_file.zip", "w") {|f| f.write encoded_data}
unzip_file("#{RAILS_ROOT}/zip_archive/zip_file.zip", "#{RAILS_ROOT}/unzipped/")
...(using @file_path, do stuff)
end
def unzip_file (file, destination)
destination = File.join(destination, File.basename(file, ".zip"))
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path) unless File.exist?(f_path)
}
}
@file_path = destination
end
但是,我无法正确保存zip文件。保存后的文件在解压缩部分发生错误。
Zip::ZipError (Zip end of central directory signature not found):
rubyzip (0.9.4) lib/zip/zip.rb:1287:in `get_e_o_c_d'
rubyzip (0.9.4) lib/zip/zip.rb:1235:in `read_e_o_c_d'
rubyzip (0.9.4) lib/zip/zip.rb:1260:in `read_from_stream'
rubyzip (0.9.4) lib/zip/zip.rb:1392:in `initialize'
rubyzip (0.9.4) lib/zip/zip.rb:1392:in `open'
rubyzip (0.9.4) lib/zip/zip.rb:1392:in `initialize'
rubyzip (0.9.4) lib/zip/zip.rb:1410:in `new'
rubyzip (0.9.4) lib/zip/zip.rb:1410:in `open'
app/controllers/pdf_controller.rb:37:in `unzip_file'
app/controllers/pdf_controller.rb:13:in `get_pdf'
当我试图打开的文件的应用还外,该文件没有得到开说
[/home/prince/Desktop/test_project/zip_archive/zip_file.zip]
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
zipinfo: cannot find zipfile directory in one of /home/prince/Desktop/test_project/zip_archive/zip_file.zip or
/home/prince/Desktop/test_project/zip_archive/zip_file.zip.zip, and cannot find /home/prince/Desktop/test_project/zip_archive/zip_file.zip.ZIP, period.
我试着将文件保存与File.open("..", "wb")
写在二进制模式的内容,但那么也会发生相同的错误。在解码之前我应该对params[:zip]
做些什么吗?
但我传递文件到一个块并关闭块。我已经读过关闭该块的文件也被关闭。无论如何,我会尝试通过明确关闭文件。谢谢... – rubyprince 2011-03-17 11:25:27
已编辑答案 - 快速早晨回复。是的,该块将关闭该文件。我发布它的例子起作用。 – 2011-03-17 11:26:55
nope.it也没有工作... – rubyprince 2011-03-17 11:35:31