I'm trying to download excel using flask and Ajax, I used POST METHOD because there's many data to passed (JSON). but i got error 'method not allowed' when return excel. But when i used GET METHOD, it can return my excel file, but i can't get my JSON data in server.
Here's my code when i use POST:
def post(self):
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()
filename = 'excel'+".xls"
worksheet.merge_range('A2:E2', 'WORK!!')
workbook.close()
response = make_response(output.getvalue())
response.headers['Content-Type'] = "application/x-xlsx"
response.headers["Cache-Control"] = "no-cache"
response.headers["Content-Disposition"] = "attachment; filename="+filename
return response
here's my ajax code:
$.ajax({
url: '/downloadFile',
type: 'POST',
data: JSON.stringify({
data1: data1,
data2: data2
}),
dataType: "JSON",
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
alert('ok')
window.location = this.url;}})
i can't do this thing using AJAX but i tried using XMLHttpRequest and it worked.
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response);
a.download = "-Download"+full_date+".xlsx"
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
};
xhttp.open("POST", '/downloadFile/');
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.responseType = 'blob';
xhttp.send(JSON.stringify({ data1: data1, data2: data2}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.