2011-03-17 77 views
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]做些什麼嗎?

回答

3

工程就像一個魅力。 File#open塊應正確寫入和關閉文件,您可能只是在某處有錯誤的路徑。如果File.exists?和decode64經過,你應該很好。

ruby-1.9.2-p0 > zip = "UEsDBAoAAAAAAKphcT4AAAAAAAAAAAAAAAAFABwAZW1wdHlVVAkAA8/sgU3P\n7IFNdXgLAAEE9QEAAAQUAAAAUEsBAh4DCgAAAAAAqmFxPgAAAAAAAAAAAAAA\nAAUAGAAAAAAAAAAAAKSBAAAAAGVtcHR5VVQFAAPP7IFNdXgLAAEE9QEAAAQU\nAAAAUEsFBgAAAAABAAEASwAAAD8AAAAAAA==\n" 
ruby-1.9.2-p0 > File.open('test2.zip', 'wb') {|f| f.write(Base64.decode64(zip))} 
=> 160 
ruby-1.9.2-p0 > Zip::ZipFile.open('test2.zip') {|z| z.each {|f| puts f.name}} 
empty 
=> [empty] 
+0

但我傳遞文件到一個塊並關閉塊。我已經讀過關閉該塊的文件也被關閉。無論如何,我會嘗試通過明確關閉文件。謝謝... – rubyprince 2011-03-17 11:25:27

+0

已編輯答案 - 快速早晨回覆。是的,該塊將關閉該文件。我發佈它的例子起作用。 – 2011-03-17 11:26:55

+0

nope.it也沒有工作... – rubyprince 2011-03-17 11:35:31