簡體   English   中英

下載 Excel 使用 AJAX(POST 方法)和 Flask-Restful Python

[英]Download Excel using AJAX (POST METHOD) with Flask-Restful Python

我正在嘗試使用 flask 和 Ajax 下載 excel,我使用了 POST 方法,因為有很多數據要傳遞 (JSON)。 但是當返回 excel 時出現錯誤“方法不允許”。但是當我使用 GET METHOD 時,它可以返回我的 excel 文件,但我無法在服務器中獲取我的 JSON 數據。

這是我使用 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

這是我的 ajax 代碼:

$.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;}})

我不能使用 AJAX 做這件事,但我嘗試使用 XMLHttpRequest 並且它有效。

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}));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM