1. 程式人生 > >rubyzip 壓縮文件夾時遇到Errno::EACCES (Permission denied @ rb_sysopen -

rubyzip 壓縮文件夾時遇到Errno::EACCES (Permission denied @ rb_sysopen -

說明 exists spec AD 常用 ive help AI mark

最近在做下載html頁面的時候,用了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" # 某個path下的folder
output_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()

這時出現了Errno::EACCES (Permission denied @ rb_sysopen的錯誤。

它的意思應該是沒有權限打開文件。

按照這個思路分析,去排查權限的問題,但權限都是正常的,沒有什麽問題。

再去看說明文檔,發現了其中的原由,文檔裏有這麽一段:

# 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對象。

而我傳入的Rails.root.join(download_path, "report.zip"),是一個Pathname對象,這導致了錯誤的出現。

我們平常在rails裏較為常用的Rails.root.join和File.join的區別就是返回的對象不同,並且Rails.root使用時也可以像字符一樣,以致我都認為它就是返回的字符串,所以才導致了這樣的錯誤,以後還是要仔細些才行,不要再犯同樣的錯誤,特此mark一下。

rubyzip 壓縮文件夾時遇到Errno::EACCES (Permission denied @ rb_sysopen -