Rails 如何 zip 网络文档,并且 save 到 computer

bruceyue · November 21, 2013 · Last by bruceyue replied at March 04, 2014 · 2124 hits

def index
  @downloads = get_all_downloads
end   

def get_all_downloads
  return SfDownload.where(is_active: true)
end  

def download
  require 'zip'
  require 'open-uri'
  if get_all_downloads
    zipfile_name = "SfDocuments.zip"
    Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
      get_all_downloads.each do |sfd|
        # Two arguments:
        # - The name of the file as it will appear in the archive
        # - The original file, including the path to find it
        zipfile.add(File.basename(sfd.sf_url), open(sfd.sf_url))
      end
    end
  end
end

SfDownload 中保存了网络 url, 我想做个页面,将选中的 Url 打包,然后点击下载按钮保存到电脑里,如何实现呢?

下面只是思路。

require 'zip'
require 'open-uri'

def download
  # 从网页端发回选中的url集合
  selected_url = params[:selected_url]
  zipfile_name = "SfDocuments.zip"
  Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
    selected_url.each do |url|
       # 大文件可能需要curl或者wget之类的工具吧。
       response = open(url)
       file  = File.open('file_name', w) # file_name 需要自己设置
       file.write response.body
       file.close
       zipfile.add file  # 打包返回网页内容
    end
  end
end

如果需要下载比较大的内容 比如视频,返回压缩包的时候 用户怕是等不了那么久把。

只有文档可能的最大允许数量也就 20M 多点。

@bruceyue 建议吧每个 url 的下载任务分开到 worker 里面 然后异步方式返回压缩包下载地址

@shawnyu 如何讲下载人物下载任务分开到 worker 里面呢?

You need to Sign in before reply, if you don't have an account, please Sign up first.