I am trying to build a form in my Rails app where the user can select a file extension from a select box and then the selected file gets downloaded.
Form:
select_tag :data_export, options_for_select(format_options)
Form helper:
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
Controller action:
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;
}
});
The code works and the selected file gets downloaded. But it also throws (minor) errors in Chrome and Safari such as:
Resource interpreted as Document but transferred with MIME type text/csv
Is there an alternative to the approach above, possibly using Ajax?
Thanks for any help.