压缩 zip 中的 JSON 响应并在用户点击 Rails 中的 h URL 时下载



我是 Rails 的新手。 我想压缩 zip 格式的 JSON 响应,并在用户点击特定 URL 时下载它。我的控制器代码如下

api :GET, '/tv/latest', 'Get latest tvs.'
  error :code => 401, :desc => "Unauthorized"
  description "Get latest tvs."
  example 'curl -i -H "Accept: application/json" -d "auth_token=nu8vh5GqmVxMHurhRyYz" -X GET http://localhost:3000/tv/latest'
def latest
    @tvs = Tv.where(:approved_cd => 0).order('tvs.first_air_date DESC').page(params[:page]).per(12)
    count = Tv.where(:approved_cd=>0).count
    respond_to do |format|
    format.json { render :json =>{:tvs=>JSON.parse(@tvs.to_json(request_type: "index")), :count=>count}}
    end
  end 

我正在尝试这个。

  def latest
    @tvs = Tv.where(:approved_cd => 0).order('tvs.first_air_date DESC').page(params[:page]).per(12)
    count = Tv.where(:approved_cd=>0).count
    require 'rubygems'
    require 'zip'
    folder = "Users/me/Desktop/stuff_to_zip"
    input_filenames = ['image.jpg', 'description.txt', 'stats.csv']
    zipfile_name = "/Users/me/Desktop/archive.zip"
    Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
      input_filenames.each do |filename|
        # 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(filename, folder + '/' + filename)
      end
      zipfile.get_output_stream("myFile") { |os| os.write "myFile contains just this" }
    end
    respond_to do |format|
    format.json { render :json =>{:tvs=>JSON.parse(@tvs.to_json(request_type: "index")), :count=>count}}
    format.zip { send_file file }
    end
  end

请修改它,以便我可以获取 zip 格式@tvs数组并在点击时下载它

http://localhost:3000/tv/latest

谢谢

试试这个:

def latest
  @tvs = Tv.where(:approved_cd => 0).order('tvs.first_air_date DESC').page(params[:page]).per(12)
  count = Tv.where(:approved_cd=>0).count
  request.env['HTTP_ACCEPT_ENCODING'] = 'gzip'
  respond_to do |format|
    format.json { render :json =>{:tvs=>@tvs, :count=>count}}
  end
end 

相关内容

  • 没有找到相关文章

最新更新