我的控制器中有此代码,并希望使zip文件受密码保护。
我尝试过rubyzip https://github.com/rubyzip/rubyzip#password-protection-experimental中的此解决方案,但没有运气。反正我能做到吗?
def export
@user = current_user
@user_gdpr_profile = @user.gdpr || @user.build_gdpr
# CSV File 1: user_profile
if @user.user_profile.present?
headers = UserProfile.new.attributes.keys
headers.delete('created_at')
logger.info "headers: #{headers.inspect}"
res = CSV.generate(headers: true) do |csv|
csv << headers
csv << headers.map{ |attr|
value = @user.user_profile.send(attr.to_sym)
value
}
end
else
res = nil
end
zipfile_name = "#{Rails.root}/public/#{@user.email}.zip"
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
zipfile.get_output_stream("user_profile.csv") { |f| f.write res }
end
send_file(File.join("#{Rails.root}/public/", "#{@user.email}.zip"), :type => 'application/zip', filename: "#{@user.email}.zip")
file = "#{@user.email}.zip"
end
更新[0]
我确实遵循了Generating password protected zip files from ruby on rails,但它有点过时了,因此无法在我最新的Rails 5和ruby 2.5.1中工作
更新[01]
我尝试过:
Zip::OutputStream.write_buffer(::StringIO.new(''), Zip::TraditionalEncrypter.new('password')) do |zos|
zos.put_next_entry("user_profile.csv")
zos.write res
end.string
它已保存,但无法打开zip文件。我在代码中的某处做错了什么吗?