最近在做下載html頁(yè)面的時(shí)候,用了rubyzip包,它的說明文檔里有這樣一段可以直接拿來用的
require'zip'# This is a simple example which uses rubyzip to# recursively generate a zip file from the contents of# a specified directory. The directory itself is not# included in the archive, rather just its contents.#
# Usage:#? directory_to_zip = "/tmp/input"#? output_file = "/tmp/out.zip"#? zf = ZipFileGenerator.new(directory_to_zip, output_file)#? zf.write()class ZipFileGenerator
? # Initialize with the directory to zip and the location of the output archive.def initialize(input_dir, output_file)
? ? @input_dir = input_dir
? ? @output_file = output_file
? end
? # Zip the input directory.def write
? ? entries = Dir.entries(@input_dir) - %w(. ..)
? ? ::Zip::File.open(@output_file, ::Zip::File::CREATE) do |zipfile|? ? ? write_entries entries, '', zipfile
? ? end
? end
? private
? # A helper method to make the recursion work.def write_entries(entries, path, zipfile)
? ? entries.each do |e|? ? ? zipfile_path = path =='' ? e : File.join(path, e)
? ? ? disk_file_path = File.join(@input_dir, zipfile_path)
? ? ? puts "Deflating #{disk_file_path}"if File.directory? disk_file_path
? ? ? ? recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
? ? ? else? ? ? ? put_into_archive(disk_file_path, zipfile, zipfile_path)
? ? ? end
? ? end
? end
? def recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
? ? zipfile.mkdir zipfile_path
? ? subdir = Dir.entries(disk_file_path) - %w(. ..)
? ? write_entries subdir, zipfile_path, zipfile
? end
? def put_into_archive(disk_file_path, zipfile, zipfile_path)
? ? zipfile.get_output_stream(zipfile_path) do |f|? ? ? f.write(File.open(disk_file_path, 'rb').read)
? ? end
? end
end
于是按照說明直接使用,我的代碼如下:
report_path ="path/folder"# 某個(gè)path下的folderoutput_file = Rails.root.join(download_path,"report.zip")
File.delete(output_file) if File.exists?(output_file)
zf = ZipFileGenerator.new(report_path, output_file)
zf.write()
這時(shí)出現(xiàn)了Errno::EACCES (Permission denied @ rb_sysopen的錯(cuò)誤。
它的意思應(yīng)該是沒有權(quán)限打開文件。
按照這個(gè)思路分析,去排查權(quán)限的問題,但權(quán)限都是正常的,沒有什么問題。
再去看說明文檔,發(fā)現(xiàn)了其中的原由,文檔里有這么一段:
# Usage:#? directory_to_zip = "/tmp/input"#? output_file = "/tmp/out.zip"#? zf = ZipFileGenerator.new(directory_to_zip, output_file)#? zf.write()
這說明directory_to_zip和output_file都是string對(duì)象。
而我傳入的Rails.root.join(download_path,"report.zip"),是一個(gè)Pathname對(duì)象,這導(dǎo)致了錯(cuò)誤的出現(xiàn)。
我們平常在rails里較為常用的Rails.root.join和File.join的區(qū)別就是返回的對(duì)象不同,并且Rails.root使用時(shí)也可以像字符一樣,以致我都認(rèn)為它就是返回的字符串,所以才導(dǎo)致了這樣的錯(cuò)誤,以后還是要仔細(xì)些才行,不要再犯同樣的錯(cuò)誤,特此mark一下。