Rails send_file / send_data - 无法读取文件 - 在Web服务调用

时间:2016-08-24 20:35:11

标签: ruby-on-rails xml file streaming sendfile

My Rails 3.1应用程序进行Web服务调用以获取pdf文件,然后我需要将其发送到浏览器进行下载。

XML响应是这样的:

<RenderResponse>
  <Result>blahblah this is the file info<Result>
  <Extension>PDF</Extension>
  <MimeType>application/pdf</MimeType>
</RenderResponse>

然后我试图转换&#34;结果&#34;如此标记到文件:

@report = @results[:render_response][:result]
@report_name = MyReport.pdf
File.open(@report_name, "w+") do |f|
  f.puts @report
end

最后我尝试发送到浏览器:

send_file File.read(@report_name), :filename => @report_name, :type => "application/pdf; charset=utf-8", :disposition => "attachment"

这会产生一个错误,表示&#34;无法读取文件&#34;它会从结果标记中吐出所有文本。

如果我这样使用send_data:

send_data File.read(@report_name).force_encoding('BINARY'), :filename => @report_name, :type => "application/pdf; charset=utf-8", :disposition => "attachment"

下载有效,但是我得到一个0KB的文件和一个说明文件&#34; MyReport.pdf&#34;的Adobe错误。无法打开,因为&#34;它不是受支持的文件类型,或者已经损坏&#34;。

如何获取XML响应文件信息,创建文件并流式传输到浏览器?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 send_file是正确的流机制,但我需要在写入文件时解码字符串。我还需要添加&#39; b&#39; File.open调用的参数。

这有效:

File.open(@report_name, "wb+") do |f|
  f.puts Base64.decode64(@report)
end



@file = File.open(@report_name, 'r')

   send_file @file, :filename => @report_name, :type => "application/pdf; charset=utf-8", :disposition => "attachment"