使用 Sinatra 的附件方法发送 zip 文件不起作用
Sending a zip file with Sinatra's attachment method not working
我正在构建一个用于管理订阅和生成邮件列表的应用程序。
我正在我的应用程序中构建一项功能,以将每个订阅下的所有邮件列表导出为多个 csv。这将生成一个 zip 文件,其中包含所有各种 csv。然后我使用Sinatra中的attachment方法将文件发送给用户
但是,每当我执行此操作时,用户都会得到一个小于 1KB 的 zip 文件,但没有任何数据 - 但是当我查看服务器上的文件时,zip 文件就在那里,并且包含所有数据其中的数据。
知道为什么用户下载的附件没有任何数据吗?
我用来创建 zip 文件并将其发送给用户的代码:
require 'zip'
get '/all' do
zip_name = 'all_mailing_lists.zip'
File.delete(zip_name) if File.exists?(zip_name) # Delete previous version if it exists
# Get a list of all csv files alrady created and delete them
Dir.glob("./exports/*.csv") do |filepath|
File.delete(filepath) if File.exists?(filepath)
end
subscriptions = Subscription.all # Get all subscriptions into an array
# Iterate through all subscriptions and export to csv
subscriptions.each do |subscription|
export = ExportCsv.new
mailing_list = export.export_mailing_list(subscription)
# Create the csv
File.open("./exports/#{subscription.name}_mailing_list.csv", 'w+') do |file|
file << mailing_list.to_s
end
end
# Zip all csv files
Zip::File.open(zip_name, Zip::File::CREATE) do |zipfile|
# Find all .csv files in the exports directory
Dir.glob("./exports/*.csv") do |filepath|
filename = filepath.split("/").pop
zipfile.add(filename, filepath)
end
end
# Download zip file
attachment("./all_mailing_lists.zip")
File.read("./all_mailing_lists.zip")
end
提前致谢!
所以,我发现 Sinatra 有一个名为 send_file
的不同方法,在这种情况下比 attachment
方法效果更好。
使用 send_file
代替 attachment
效果很好。
我正在构建一个用于管理订阅和生成邮件列表的应用程序。
我正在我的应用程序中构建一项功能,以将每个订阅下的所有邮件列表导出为多个 csv。这将生成一个 zip 文件,其中包含所有各种 csv。然后我使用Sinatra中的attachment方法将文件发送给用户
但是,每当我执行此操作时,用户都会得到一个小于 1KB 的 zip 文件,但没有任何数据 - 但是当我查看服务器上的文件时,zip 文件就在那里,并且包含所有数据其中的数据。
知道为什么用户下载的附件没有任何数据吗?
我用来创建 zip 文件并将其发送给用户的代码:
require 'zip'
get '/all' do
zip_name = 'all_mailing_lists.zip'
File.delete(zip_name) if File.exists?(zip_name) # Delete previous version if it exists
# Get a list of all csv files alrady created and delete them
Dir.glob("./exports/*.csv") do |filepath|
File.delete(filepath) if File.exists?(filepath)
end
subscriptions = Subscription.all # Get all subscriptions into an array
# Iterate through all subscriptions and export to csv
subscriptions.each do |subscription|
export = ExportCsv.new
mailing_list = export.export_mailing_list(subscription)
# Create the csv
File.open("./exports/#{subscription.name}_mailing_list.csv", 'w+') do |file|
file << mailing_list.to_s
end
end
# Zip all csv files
Zip::File.open(zip_name, Zip::File::CREATE) do |zipfile|
# Find all .csv files in the exports directory
Dir.glob("./exports/*.csv") do |filepath|
filename = filepath.split("/").pop
zipfile.add(filename, filepath)
end
end
# Download zip file
attachment("./all_mailing_lists.zip")
File.read("./all_mailing_lists.zip")
end
提前致谢!
所以,我发现 Sinatra 有一个名为 send_file
的不同方法,在这种情况下比 attachment
方法效果更好。
使用 send_file
代替 attachment
效果很好。