【问题标题】:Create zip from paperclip attachments and download从回形针附件创建 zip 并下载
【发布时间】:2017-12-19 14:42:43
【问题描述】:

尝试创建一个包含很多图片的zip文件,我的代码如下:

       compressed_filestream = Zip::OutputStream.write_buffer do |zos|
      @pictures.each do |p|
        image_url = p.picturefile.url(:original)
        zos.put_next_entry p.picturefile_file_name
        zos.print(URI.parse(image_url))    
      end
    end
    compressed_filestream.rewind
    send_data compressed_filestream.read, filename: "pictures.zip"

这会创建一个pictures.zip 文件,但它只包含每张图片的text-url 而不是实际的图片...

【问题讨论】:

  • 您需要文件的路径而不是 URL 吗?
  • 尝试读取文件,然后写入 zip。 Paperclip.io_adapters.for(p.picturefile).read.

标签: ruby-on-rails zip paperclip zipoutputstream


【解决方案1】:

现在您只是将图像的 URL 传递给文件。您需要做的就是将行内容传递给它。

compressed_filestream = Zip::OutputStream.write_buffer do |zos|
  @pictures.each do |p|
    zos.put_next_entry p.picturefile_file_name
    zos.print(Paperclip.io_adapters.for(p.picturefile).read)    
  end
end
compressed_filestream.rewind
send_data compressed_filestream.read, filename: "pictures.zip"

【讨论】:

  • 如果我需要提供一个 url 来下载这个 zip,我应该怎么做?
【解决方案2】:

添加到上面提供的解决方案,

如果您想将其保存在本地,并提供稍后或通过 API 下载此 zip 文件的路径

compressed_filestream = Zip::OutputStream.write_buffer do |zos|
  @pictures.each do |pic|
    zos.put_next_entry pic.upload_file_name
    zos.write(Paperclip.io_adapters.for(pic.upload.url).read)
  end
end
File.open("#{Rails.root}/public/system/#{file_name}", 'wb') { |f| f.write(compressed_filestream.string) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    相关资源
    最近更新 更多