Reputation: 9822
I have a rails server that generates a csv from an http request, like this:
@results = some_json_string
require 'csv'
csv_string = CSV.open("results.csv","wb") do | csv|
JSON.parse(@results).each do |hash|
csv << hash.values
end
end
send_file('results.csv')
And an AngularJS application that requests this CSV file from the server
angular.module('myApp')
.controller('QueryCtrl', ['$scope', 'Query', function ($scope, Query) {
$scope.csvSubmit = function() {
var csv = $.post('http://ip_addr:3000/api/csv', { 'input': 'my_request' });
csv.done(function(result){
File.save(result, function(content){
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/csv,' + encodeURI(content);
hiddenElement.target = '_blank';
hiddenElement.download = 'result.csv';
hiddenElement.click();
});
});
}
}
])
It seems that, as the Angular app makes the http request, the Rails server sends over the csv file.
From the rails logs:
GET /professional/maintain/status/ 200 224 - - 0 2908 - -\n"}
Sent file results.csv (0.1ms)
Completed 200 OK in 976ms (ActiveRecord: 0.0ms)
However, the Angular app does not successfully download the file to the client machine. Instead, the javascript console shows this error:
Uncaught TypeError: undefined is not a function query.js:8
line 8 is this line:
File.save(result, function(content){
Anyone have an idea how to get this download working correctly?
EDIT: It could be a syntax thing, since I haven't actually written that much javascript. Bust as I'm looking at it I can't figure out why it would tell me undefined is not a function.
Upvotes: 0
Views: 2011
Reputation: 201
File has no method save MDN documentation, you should be able to accomplish the download via
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/csv,' + encodeURI('test,1234,1232,test');
hiddenElement.target = '_blank';
hiddenElement.download = 'result.csv';
hiddenElement.click();
Without any of the File.save(result, function(content){}); functionality
Running the above code in console starts a download with the content I passed in.
Upvotes: 2