Reputation: 511
I am having an issue when trying to create a download link that will (1) generate a CSV file in-situ and (2) commence the download automatically without being redirected to another page (i.e. AJAX request).
What happens is as follows: I am not seeing any JavaScript errors and the handler CSVDownload also executes without any issues. However, the download never starts. For some reason, if I just enter the URL (..website../csvdownload) then it does create the file using the same handler. Any idea as to why this is?
Any help would be greatly appreciated!
HTML
<button id="mainReportDownload" type="button">
Download Report
</button>
AJAX request
$('#mainReportDownload').on('click', function() {
$.ajax({
type: 'GET',
url: "/csvdownload",
beforeSend: function() {
notification('Creating report..','info',false)
}
});
});
Python
def List2CSV(data):
csv = ""
for row in data:
for item in row:
csv = csv + item + ','
csv = csv[:-1] + '\n'
csv = csv[:-1]
return csv
class CSVDownload(webapp2.RequestHandler):
def get(self):
conn = rdbms.connect(instance=_INSTANCE_NAME, database='test')
cursor = conn.cursor()
cursor.execute('SELECT email FROM Test LIMIT 100')
testvalues = [[item for item in row] for row in cursor.fetchall()]
csv = List2CSV(testvalues)
self.response.headers['Content-Type'] = 'text/csv'
self.response.headers['Content-Disposition'] = 'attachment; filename=report.csv'
self.response.out.write(csv)
conn.close()
Upvotes: 0
Views: 1591
Reputation: 600059
You have contradictory requirements. A normal download happens when the browser navigates to a URL which sends back an 'attachment' content-disposition. But you're trying to use Ajax, which doesn't navigate so no download is done. The Ajax is happily reading the content, but then simply throwing it away because you don't define a success handler telling it what to do with it. And, of course, even if you did define that handler, there's no way in Javascript to save a file to the user's computer, for obvious security reasons.
Upvotes: 1