如何使用Rails和jQuery通过选择选项下载文件?

时间:2018-12-21 17:39:31

标签: jquery ruby-on-rails ruby ajax

我正在尝试在Rails应用程序中构建一个表单,用户可以在其中从选择框中选择文件扩展名,然后下载所选文件。


表格:

select_tag :data_export, options_for_select(format_options)

表单助手:

def format_options
  options = []
  options << ["Please select...", nil]
  %w(csv xml xlsx).each do |format|
    options << [ format.upcase, invoices_path(:format => format) ]
  end
  options
end

控制器操作:

def index
  @invoices = Invoice.all
  respond_to do |format|
    format.csv {  send_data(invoices_file(:csv),  filename: 'invoices.csv',  disposition: 'attachment') }
    format.xlsx { send_data(invoices_file(:xlsx), filename: 'invoices.xlsx', disposition: 'attachment') }
    format.xml {  send_data(invoices_file(:xml),  filename: 'invoices.xml',  disposition: 'attachment') }
  end
end

jQuery:

$('#data_export').on('change', function() {
  var url = $(this).val();
  if (url) {
    location = url;
  }
});

代码有效,并且所选文件被下载。但这也会在Chrome和Safari中引发(轻微)错误,例如:

  

资源被解释为文档,但以MIME类型传输   文字/ csv

是否可以使用Ajax替代上述方法?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

也许您可以考虑将send_data用于这样的下载:

  def index
    @invoices = Invoice.all
    respond_to do |format|
      format.csv { send_data(invoices_file(:csv), filename: 'invoices.csv', disposition: 'attachment') }
      format.xlsx { send_data(invoices_file(:xlsx), filename: 'invoices.xlsx', disposition: 'attachment') }
      format.xml { send_data(invoices_file(:xml), filename: 'invoices.xml', disposition: 'attachment') }
    end
  end

答案 1 :(得分:0)

好的,我无法删除错误,但我意识到这些错误不是由于我使用选择框,而是在尝试从invoices_path下载时发生的。可以通过在下载链接中添加:download => :download来消除错误。因此,我从选择框切换为链接,现在错误消失了。 This other question here on SO helped me a lot