2012-02-13 29 views
5

Trên thực tế tôi đang làm một cái gì đó như thế này:Tải Kẹp giấy các file như ZIP

project   = Project.find(params[:id]) 
attachments_list = project.attachments.where{attach_file_size > 0} 
assets_list  = project.assets.where{image_file_size > 0} 
#Person.where{(name =~ 'Ernie%') & (salary < 50000) | (name =~ 'Joe%') & (salary > 100000)} 
file_name = project.title.downcase.gsub(' ', '_destroy') 
file_name = "#{file_name}.zip" 

temp_file = Tempfile.new("#{file_name}-#{current_user.id}") 
Zip::ZipOutputStream.open(temp_file.path) do |zos| 
    attachments_list.each do |file| 
    zos.put_next_entry(file.title) 
    zos.print IO.read(file.attach.path) 
    end 
    assets_list.each do |file| 
    zos.put_next_entry(file.title) 
    zos.print IO.read("#{file.image.path}") 
    end 
end 

send_file temp_file.path, :type => 'application/zip', 
          :disposition => 'attachment', 
          :filename => file_name 
temp_file.close 

Đó là công việc nhưng phần mở rộng là mất tích trên các tập tin đã nhận, bất kỳ ý tưởng?

Trả lời

2

cuối cùng tôi thực hiện một phương pháp bên trong mô hình liên quan để trả lại tên tập tin với tiện ích mở rộng

def title_with_ext 
    "#{self.title}#{File.extname(self.image.path)}" 
end 
0

Chỉ cần thay đổi :filename => file_name để :filename => file_name.zip

:type chỉ xác định các ứng dụng mà sẽ sử dụng các tập tin, nhưng không phải là phần mở rộng cho tên tập tin

+0

.zip không bỏ lỡ tệp lưu trữ mà tệp bị bỏ lỡ bên trong – Awea

1

Tôi đã làm một việc tương tự nhưng cần thiết để lấy tệp từ S3 thay vì hệ thống cục bộ. Các tệp của tôi không lớn, vì vậy tôi đã quyết định chỉ tải chúng vào bộ nhớ. Vì vậy, thay vì điều này:

zos.print IO.read(file.attach.path) 

Tôi đã thêm một require "open-uri" và sau đó đã làm điều này:

zos.print open(asset.data.url) {|f| f.read} 

đâu asset là một đối tượng kẹp giấy.

Các vấn đề liên quan