Ruby on Rails - Zip/HTTParty

6g8kf2rb  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(78)

我有一个API请求,返回多个(Word)文件要下载,但我不能在while循环中发送_data,否则我会得到可怕的多重渲染错误,所以我的问题是我如何打包/合并/zip/解析多个,这样我就可以发送_data一次?
这里是块:

def generate_multi_letter(template, letterName, params)
@Document_URL = "#{ENV["API_HOST"]}/api/StateDocument/GenerateDocX/#{template}"
response = HTTParty.post(@Document_URL,
                         :body => params,
                         :headers => { "Content-Type" => "application/json" })

Zip::InputStream.open(StringIO.new(response)) do |io|
while entry = io.get_next_entry
            report = io.read
            send_data report,
              :filename => letterName + ".docx",
              :type => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
              disposition: "attachment"
          end

或者更像是.....?

Zip::File.open(response, Zip::File::CREATE) do |zip|
  Attachment.all.each do |attachment|
    file = Tempfile.new("#{attachment.created_at.in_time_zone}.docx")
    file.write(attachment.image_string)
    zipfile.add("#{attachment.created_at.in_time_zone}.docx", file.path)
  end
end

zip_data = File.read(response)
send_data(zip_data, type: 'application/zip', disposition: 'attachment', filename: letterName + ".docx")

我也得到“路径名包含空字节”的错误,如果有人指出我在那里出错??

nkkqxpd9

nkkqxpd91#

对于任何跟随的人来说,这变得非常简单,只需信任浏览器,并返回整个响应(只要您将mime类型定义为.zip):

@URL = "#{ENV["API_HOST"]}/api/GenerateDocX/#{template}"
response = HTTParty.post(@URL,:body => params,:headers => { "Content-Type" => "application/json" })

send_data response, :filename => letterName + ".zip", type: 'application/zip'

相关问题