[英]RubyZip set file timestamps
我整天都在为此而烦恼,也许您能帮上忙吗? 我使用RubyZip压缩文件,我需要将该文件的创建/更新/修改时间设置为时区中的特定时间(这取决于我在@time_zone
变量中拥有的客户端时区)。
我知道这很可能是超级错误,我从RubyZip测试文件中获取了魔术字符串'UT\\x5\\0\\x3\\250$\\r@Ux\\0\\0'
,但我不知道这是什么。 大声笑。 但是-我现在可以在PC上运行它。 它实际上会压缩文件并根据指定的时区为其设置正确的时间戳。
但是-它在应用服务器上不起作用,因为OS时区位于UTC时区。 它为不匹配的文件生成其他时间。
这是我使它起作用的程度:
def save_to_zip(file_path)
Zip::OutputStream.open(file_path) do |out|
@sheets.each do |csv|
name = csv.name
extra = time_for_zip
out.put_next_entry("#{name}.#{@file_extension}", nil, extra)
tmpfile = csv.tmpfile
tmpfile.close
source = File.open(tmpfile.path, 'r')
source.each do |line|
out.write(line)
end
end
end
end
def time_for_zip
return nil if @time_zone.blank?
timestamp = Zip::ExtraField.new('UT\x5\0\x3\250$\r@Ux\0\0')
localtime_str = Time.now.in_time_zone(@time_zone).strftime("%Y-%m-%dT%H:%M:%S")
dos_time_in_store_tz = ::Zip::DOSTime.parse(localtime_str)
timestamp['UniversalTime'].ctime = dos_time_in_store_tz
timestamp['UniversalTime'].atime = dos_time_in_store_tz
timestamp['UniversalTime'].mtime = dos_time_in_store_tz
timestamp
end
您能告诉我如何在zip文件中正确设置文件时间吗?
非常感谢...
马里斯
像这样解决:
def save_to_zip(file_path)
Zip::OutputStream.open(file_path) do |out|
@sheets.each do |csv|
name = csv.name
tmpfile = csv.tmpfile
tmpfile.close
source = File.open(tmpfile.path, 'r')
zip_entry = Zip::Entry.new(out, "#{name}.#{@file_extension}", nil, nil, nil, nil, nil, nil, time_for_zip(source.ctime))
out.put_next_entry(zip_entry)
source.each do |line|
out.write(line)
end
end
end
end
def time_for_zip(file_time)
return Zip::DOSTime.at(file_time) if @time_zone.blank?
Zip::DOSTime.parse(file_time.utc.in_time_zone(@time_zone).strftime("%Y-%m-%d %H:%M:%S"))
end
对此线程的荣誉: https : //github.com/rubyzip/rubyzip/pull/40
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.