2016-04-27 27 views
1

我正在嘗試編寫rails測試(使用水豚& Poltergeist)來測試.zip文件的下載功能。從二進制數據寫入.zip文件

我有一個從XHR請求返回的.zip文件的二進制數據,我希望將這些數據寫入本地的.zip文件,並從那裏進行進一步的測試。
下面的方法模擬上點擊一個按鈕,當應用程序內,返回已選中所有文件的zip文件:

# Perform XHR 
def download_file(link) 
    page.execute_script("window.downloadFile = function(){ var url = window.location.protocol + '//' + window.location.host + '#{link}'; return getFile(url); }") 
    page.execute_script("window.getFile = function(url){ var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.responseType = 'blob'; xhr.send(); return xhr.response; }") 

    begin 
    file = page.evaluate_script('downloadFile()') 
    rescue 
    raise "Error during XHR. Is url valid?" 
    end 
    file 
end 

我想寫的響應在這裏提交:

file = download_file(url) 
file_path = "#{Rails.root}/tmp/files/download.zip" 
File.open(file_path, 'wb'){ |f| f.write file } 

當嘗試使用解壓縮unzip tmp/files/download.zip我給出以下響應生成的文件:

Archive: tmp/files/download.zip 

caution: zipfile comment truncated 
error [tmp/files/download.zip]: missing 3182550208 bytes in zipfile 
    (attempting to process anyway) 
error [tmp/files/download.zip]: start of central directory not found; 
    zipfile corrupt. 
    (please check that you have transferred or created the zipfile in the 
    appropriate BINARY mode and that you have compiled UnZip properly) 

我嘗試覆蓋的MIME類型text/plain,application/zip等,但無濟於事。
有什麼建議嗎?

回答

0

我擴展了它視爲檔案類,包括寫二元函數

class Tempfile 
    def openBinary 
     @tmpfile.close if @tmpfile 
     @tmpfile = File.open(@tmpname, 'wb') 
     @data[1] = @tmpfile 
     __setobj__(@tmpfile) 
    end 
end 

這使人們有可能對我的系統解析zip文件,然後讀取使用郵編::使用ZipFile類。