rubyzip 压缩文件夹时遇到Errno::EACCES (Permission denied @ rb_sysopen -
Posted Still_Walking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rubyzip 压缩文件夹时遇到Errno::EACCES (Permission denied @ rb_sysopen -相关的知识,希望对你有一定的参考价值。
最近在做下载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 -的主要内容,如果未能解决你的问题,请参考以下文章
如何直接从 ZipEntry(RubyZip、Paperclip、Rails 3)获取临时文件对象(内容类型正确,无需写入磁盘)?