我正在实现允许用户从S3下载单个文件或多个文件的功能。 单个文件下载工作正常,但对于多个文件我在Heroku上收到错误,
Errno::ENOENT (No such file or directory @ rb_file_s_lstat )
用于以zip格式下载文件的控制器代码段如下,
def method_name
zipfile_name = "#{Rails.root}/public/archive.zip"
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile |
@transfer.transfer_attachments.each do |attachment |
zipfile.add(attachment.avatar.file.filename, attachment.avatar.url)
end
end
send_file(File.join("#{Rails.root}/public/", 'archive.zip'), : type =>
'application/zip', : filename => "#{Time.now.to_date}.zip")
end
的Gemfile
ruby '2.3.1'
gem 'rails', '~> 5.0.1'
gem 'rubyzip', '>= 1.0.0'
gem 'zip-zip'
此zipfile功能适用于本地存储的文件。
答案 0 :(得分:4)
我想回答我的问题。 步骤如下,
这是控制器代码,
require 'open-uri'
def download_all_files
folder_path = "#{Rails.root}/public/downloads/"
zipfile_name = "#{Rails.root}/public/archive.zip"
FileUtils.remove_dir(folder_path) if Dir.exist?(folder_path)
FileUtils.remove_entry(zipfile_name) if File.exist?(zipfile_name)
Dir.mkdir("#{Rails.root}/public/downloads")
@model_object.each do |attachment|
open(folder_path + "#{attachment.avatar.file.filename}", 'wb') do |file|
file << open("#{attachment.avatar.url}").read
end
end
input_filenames = Dir.entries(folder_path).select {|f| !File.directory? f}
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
input_filenames.each do |attachment|
zipfile.add(attachment,File.join(folder_path,attachment))
end
end
send_file(File.join("#{Rails.root}/public/", 'archive.zip'), :type => 'application/zip', :filename => "#{Time.now.to_date}.zip")
end
答案 1 :(得分:1)
猜猜:您正在添加附件作为网址,但您应该添加(本地)文件路径。