0

So I'm sending an AJAX post request to my server so that I can get information and generate a file. I am able to generate the file and I can even console it in the done function using console.log(data).

I'm just not sure how to go about downloading it; I tried the solution of creating element and using js to click it but it did not seem to work.

Additional info:

I am sending the Ajax request using Jquery. The web application is a python flask application.

danny gonzalez
  • 210
  • 2
  • 10
  • 1
    You can find the answer [here](https://stackoverflow.com/q/16086162/831878) – Ray Toal Jul 13 '18 at 22:47
  • @RayToal I can't use a form element. I need to send csrf token in the header, and to do that I have to do my own ajax call, which I already do but I'm not able to download the file – danny gonzalez Jul 16 '18 at 01:52

1 Answers1

1

This might not be the best way but here's what I had to do, since my version of jquery is not the most update, I had to a save the ajax function into a varible name xhr, to get the response header

success: function (data) {
 var disposition = xhr.getResponseHeader('content-disposition');
 var matches = /"([^"]*)"/.exec(disposition);
 var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');

 var blob = new Blob([data], {type: 'application/pdf'});
 var link = document.createElement('a');
 link.href = window.URL.createObjectURL(blob);
 link.download = filename;

 document.body.appendChild(link);

 link.click();

 document.body.removeChild(link);

}

adapted from https://nehalist.io/downloading-files-from-post-requests/

danny gonzalez
  • 210
  • 2
  • 10