【问题标题】:Rails send_file rendering files as plain text on new page instead of browser downloading fileRails send_file 在新页面上将文件呈现为纯文本,而不是浏览器下载文件
【发布时间】:2017-01-01 03:21:37
【问题描述】:

调用 send_file 时,它​​会将文件发送到浏览器,但浏览器会将内容作为纯文本转储到新页面上,而不是下载文件。如果我刷新该页面,它会正常下载文件。

路线

get 'download' => 'qr_codes#download'

控制器

def download
    path = Rails.root.join("events/active/#{params[:name]}/#{params[:batch]}/#{params[:file]}")
    send_file(path, type: 'application/vnd.ms-excel', filename: params[:file])
end

查看

<%= link_to 'Original Upload', download_path(name: @event_name,
  batch: batch, file: batch_upload_filename(@event_name, batch)) %>

解决方案: 这最终成为带有涡轮链接的known issue。如果像我一样使用 Turbolinks 5,更新后的语法是:data: { turbolinks: false }

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 sendfile


    【解决方案1】:

    尝试设置处置:

    def download
      path = Rails.root.join("events/active/#{params[:name]}/#{params[:batch]}/#{params[:file]}")
      send_file(path, type: 'application/vnd.ms-excel', filename: params[:file], disposition: 'attachment')
    end
    

    或更改文件以确保扩展名正确

    "#{params[:file][0,params[:file].index(".")]}.xlsx"
    

    哦,不要将参数注入字符串来构建下载路径。我可以将“../../”注入:name,“config”,注入:batch,将“../config/database.yml”注入:file。将文件路径添加到模型。

    【讨论】:

    • 处置默认为“附件”。无论如何我尝试设置它并遇到相同的结果。根据您的建议,我还确保文件扩展名是正确的,并且得到了相同的结果。
    • 如果我直接去这里下载很好"http://localhost:3000/download?batch=1&amp;file=HSS.xls&amp;name=HSS+2016",只有当我从不同的页面链接到这个路径时,它才会在浏览器中呈现纯文本,然后正如我在帖子中提到的,刷新明文页面,然后将正常下载文件。
    【解决方案2】:

    这最终成为 turbolinks 的一个已知问题。如果像我一样使用 Turbolinks 5,更新后的语法是:

    data: { turbolinks: false }
    

    【讨论】:

      【解决方案3】:

      制作辅助方法

      def some_helper(content_type)
       Rack::Mime::MIME_TYPES.invert[content_type].gsub(/\./mi, '')
      end
      

      并将链接更新为

      <%= link_to 'Original Upload', download_path(name: @event_name, batch: batch, file: batch_upload_filename(@event_name, batch, format: file_format(attachment.file.content_type))) %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-18
        • 1970-01-01
        • 1970-01-01
        • 2014-06-29
        • 1970-01-01
        • 2016-09-11
        • 2011-11-08
        相关资源
        最近更新 更多