【问题标题】:Rails send_file/send_data - Cannot Read File - After web service callRails send_file/send_data - 无法读取文件 - 网络服务调用后
【发布时间】: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 的文件和一个 Adob​​e 错误,指出文件“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


【解决方案1】:

我找到了解决方案。 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"

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2023-03-08
    • 2017-03-01
    相关资源
    最近更新 更多