Rails 下载文件

  1. 根据request的format参数来确定返回值类型,代码如下:

    1
    2
    3
    4
    5
    6
    7
    respond_to do |format|
    format.html
    format.csv do
    headers['Content-Disposition'] = "attachment; filename='filename.csv'"
    headers['Content-Type'] ||= 'text/csv'
    end
    end
  2. 链接地址:

    1
    <%= link_to('Download Link', {:action => :download, :format => :csv}) %>
  3. 添加CSV模板文件,命名为<action_name>.csv.erb

0%