【发布时间】:2017-01-01 03:18:03
【问题描述】:
我的 Rails 3.1 应用程序调用 Web 服务以获取 pdf 文件,然后我需要将其发送到浏览器进行下载。
XML 响应是这样的:
<RenderResponse>
<Result>blahblah this is the file info<Result>
<Extension>PDF</Extension>
<MimeType>application/pdf</MimeType>
</RenderResponse>
然后我尝试将“结果”标签转换为文件:
@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"
这会产生“无法读取文件”的错误,并从结果标签中吐出所有文本。
如果我这样使用 send_data:
send_data File.read(@report_name).force_encoding('BINARY'), :filename => @report_name, :type => "application/pdf; charset=utf-8", :disposition => "attachment"
下载有效,但我得到一个 0KB 的文件和一个 Adobe 错误,指出文件“MyReport.pdf”无法打开,因为“它不是受支持的文件类型或已损坏”。
如何获取 XML 响应文件信息、创建文件并流式传输到浏览器?
【问题讨论】:
-
你可以试试这个` File.open(file, 'r') do |f| send_data f.read.force_encoding('BINARY'), :filename => 文件名, :type => "application/pdf", :disposition => "attachment" end`
-
感谢您的评论。我已经尝试过了,它并没有解决这个问题。我确实找到了解决方案并将其发布。
标签: ruby-on-rails xml file streaming sendfile