Rails send_file/send_data - 无法读取文件 - 网络服务调用后

Rails send_file/send_data - Cannot Read File - After web service call

我的 Rails 3.1 应用程序调用网络服务以获取 pdf 文件,然后我需要将该文件发送到浏览器以供下载。

XML 响应是这样的:

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

然后我尝试将 "Result" 标签转换为文件:

@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"

这会产生一个错误 "Cannot Read File",它会吐出结果标签中的所有文本。

如果我这样使用send_data:

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

下载有效,但我得到一个 0KB 的文件和一个 Adob​​e 错误,提示文件 "MyReport.pdf" 无法打开,因为 "its either not a supported file type or it has been damaged"。

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

我找到了解决方案。 send_file 是正确的流机制,但我需要在写入文件时解码字符串。我还需要将 'b' 参数添加到 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"