I’m trying to download the excel from flask using Ajax call. it’s showing the response code as 200 but excel is not downloading and the error messages are as follows.
Ajax Request :
$(“#genExcel”).on(“click”, function() {
var xhttp = new XMLHttpRequest();
// Data to post
var dataarray = {};
// Use XMLHttpRequest instead of Jquery $ajax
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
// Trick for making downloadable link
a = document.createElement('a');
const objectURL = window.URL.createObjectURL(xhttp.response);
a.href = objectURL
//const objectURL = URL.createObjectURL(object)
// Give filename you wish to download
a.download = "test-file.xlsx";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
};
// Post data to URL which handles post request
xhttp.open("POST", '/genexcel');
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
//xhttp.responseType = 'blob';
xhttp.send(JSON.stringify(dataarray));
});
Flask function :
@app.route('/genexcel', methods=["GET", "POST"])
def createExcel():
if request.method == 'POST':
data = request.json
# process json data
return send_file(strIO, attachment_filename='test.xlsx', as_attachment=True)
Errors :
1 [Report Only] Refused to evaluate a string as JavaScript because ‘unsafe-eval’ is not an allowed source of script in the following Content Security Policy directive: “script-src * blob:”.
2 Uncaught TypeError: Failed to execute ‘createObjectURL’ on ‘URL’: No function was found that matched the signature provided.
at XMLHttpRequest.xhttp.onreadystatechange
2
Answers
Here is an example using the fetch API. The first button just does a straight JS download. The second button uses the Flask route to do the download. Hope it helps.
index.html
Flask Function
Hopefully I’ve understood you correctly. Here is a very simple example using the data Array you provided. You could modify to suit your needs:
Flask Functions
index.html