rails中的send_file不会下载到浏览器 - 而是直接在浏览器窗口中加载

Pin*_*ade 2 ruby ruby-on-rails erb

我的.erb中有以下内容:

<%= link_to 'Download PDF', planners_download_pdf_url %>
Run Code Online (Sandbox Code Playgroud)

我有以下方法来回应:

  def download_pdf
  send_file(
     "#{Rails.root}/Thing/ex/example.xls",
filename: "mything.xls",
type: "application/xls"
  )
  end
Run Code Online (Sandbox Code Playgroud)

我的路线有:

get '/planners/download_pdf'
Run Code Online (Sandbox Code Playgroud)

单击我的链接时,会调用该方法.我的问题是没有下载到浏览器.相反,它采用我在浏览器中打开的选项卡并将文件转储为HTML.就像......你见过在记事本中打开的Excel文件吗?它做到了.见下文:

垃圾

如何下载该文件?

wjo*_*dan 10

您需要添加disposition: 'attachment'到您的send_file选项哈希(或至少确保您没有disposition: 'inline'设置,因为'attachment'应该是默认值).

如果这不是问题,如果您正在使用Turbolinks,如其他答案中所述,您需要通过在link元素中设置来禁用链接上的Turbolinksdata-turbolinks="false"(例如:data: {turbolinks: false}在您的link_to标记助手中).

最后,如果这不起作用,可以尝试以下其他一些事情:

  • 设置type'application/vnd.ms-excel',XLS文件的有效MIME类型.
  • 直接在链接标记上设置download="mything.xls" html5属性(例如:download: 'mything.xls'link_to标记帮助程序中).