ruby-on-rails - RubyZip 设置文件时间戳
问题描述
我整天都在为此头疼,也许你能帮忙?我正在使用 RubyZip 压缩文件,我需要将该文件创建/更新/修改的时间设置为时区中的某个时间(这取决于我在@time_zone
变量中拥有的客户端时区)。
我知道这很可能是非常不正确的,我'UT\x5\0\x3\250$\r@Ux\0\0'
从 RubyZip 测试文件中获取了那个魔术字符串,但我不知道这是什么。哈哈。但是 - 我现在已经让它在我的电脑上工作了。它真正压缩文件并根据指定的时区为其设置正确的时间戳。
但是 - 它不适用于应用服务器,因为操作系统时区位于 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
推荐阅读
- postgresql - 在 PostgresSQL 中计算阶乘函数时出现“bigint out of range”
- javascript - 我的 total_final 值不起作用,Button 也不起作用
- c++ - 如何将 .so c/cpp 库添加到 android Studio
- android - API 在 chrome 中正常调用时有效,但在 Postman 中无效
- python - 全连接神经网络无法正确预测
- charles-proxy - 每当 Charles 关闭时,macOS 代理都会自动打开。如何解决?
- php - 如何使用 PHP 连接到 WSDL Web 服务并检索其内容?
- .htaccess - htaccess 重写规则,当我在末尾添加 / 时,url 不起作用并显示错误
- c# - 转换 BitmapImage 并保存
- javascript - 使用 JQuery 从外部文件加载 div