I need to allow multiple downloading of small documents in Rails, preferably using Papercl开发者_开发百科ip (I've already used it to enable uploading).
Specific needs:
- Zip the files for download.
- Download different file types together (.jpeg, .doc, docx, .pdf).
I have found lots of tutorials online for multiple uploading, but not for downloads. I appreciate your help. Thanks!
Define a download
action on the controller that is supposed to handle the download. The method could look something like this: (Given a File
model with a paperclip attachment called attached
)
def download
require 'zip/zip'
require 'zip/zipfilesystem'
@files = File.all
t = Tempfile.new('tmp-zip-' + request.remote_ip)
Zip::ZipOutputStream.open(t.path) do |zos|
@files.each do |file|
zos.put_next_entry(file.attached_file_name)
zos.print IO.read(file.attached.path)
end
end
send_file t.path, :type => "application/zip", :filename => "Awesome.zip"
t.close
end
Add in Gemfile gem 'rubyzip'
.
#foo model
...
has_many :uploads
...
#foo controller
def download
@foo = Foo.find(params[:id])
unless @foo.uploads.empty?
send_file Upload.zip(@foo),
:type => 'application/zip',
:disposition => 'attachment',
:filename => "Foo-#{@foo.id}.zip"
end
end
#Upload model
def self.zip foo
archive = File.join("public", "files", foo.id.to_s, foo.id.to_s) +".zip"
unless File.exist? archive
files = foo.uploads.all
Zip::ZipFile.open(archive, 'w') do |zip_file|
files.each do |foo_file|
zip_file.add(foo_file.upload_file_name,foo_file.upload.path)
end
end
end
archive
end
精彩评论