2016-04-27 25 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类。