2

我是 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

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

http://localhost:3000/tv/latest

谢谢

4

1 回答 1

0

尝试这个:

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 
于 2014-12-29T11:35:48.607 回答