繁体   English   中英

使用 Ajax 和 Flask 下载 excel

[英]download excel by using Ajax andFlask

我正在尝试使用 Ajax 调用从 flask 下载 excel。 它显示响应代码为 200 但 excel 未下载,错误消息如下。

Ajax 请求:

$("#genExcel").on("点击", 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)

错误:

1 [仅报告] 拒绝将字符串评估为 JavaScript,因为“unsafe-eval”不是以下内容安全策略指令中允许的脚本源:“script-src * blob:”。

2 未捕获的类型错误:无法在“URL”上执行“createObjectURL”:未找到与提供的签名匹配的 function。

at XMLHttpRequest.xhttp.onreadystatechange

错误和响应

希望我对您的理解正确。 这是一个使用您提供的数据数组的非常简单的示例。 您可以修改以满足您的需求:

Flask 功能

from flask import Flask, render_template, request, url_for, send_file
import xlsxwriter

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/genexcel', methods=["GET", "POST"])
def createExcel():
    if request.method == 'POST':
        data = request.get_json(force=True)
        # process json data
        createExcel(data['data'])

    file_path = 'static/files/test.xlsx'
    return send_file(file_path, attachment_filename='test.xlsx', as_attachment=True)

def createExcel(data):
    workbook = xlsxwriter.Workbook('static/files/test.xlsx')
    worksheet = workbook.add_worksheet()

    row_no = 0
    col_no = 0
    for row in data:
        col_no = 0
        for entry in row:
            worksheet.write(row_no, col_no, entry)
            col_no += 1
        row_no += 1

    workbook.close()

app.run(debug=True, port=5010)

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Test</title>
  </head>
  <body>
    Testing
    <button id="genExcel">Direct Download</button>
    <button id="genExcelFlask">Flask Download</button>
  </body>

  <script>
    var btn = document.getElementById("genExcel");
    var btnFlask = document.getElementById("genExcelFlask");
    var dataArray = {
      data: [
        [1, "A", 100],
        [2, "B", 200],
      ],
    };

    btn.addEventListener("click", (e) => {
      fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then((resp) => resp.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          // the filename you want
          a.download = "todo-1.json";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          alert("your file has downloaded!"); // or you know, something with better UX...
        })
        .catch(() => alert("oh no!"));
    });

    btnFlask.addEventListener("click", (e) => {
      console.log(JSON.stringify(dataArray));

      fetch("{{ url_for('createExcel') }}", {
        method: "post",
        body: JSON.stringify(dataArray),
      })
        .then((resp) => resp.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          // the filename you want
          a.download = "test.xlsx";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          alert("your file has downloaded!"); // or you know, something with better UX...
        })
        .catch(() => alert("oh no!"));
    });
  </script>
</html>

这是一个使用提取 API 的示例。 第一个按钮只是直接下载 JS。 第二个按钮使用 Flask 路由进行下载。 希望能帮助到你。

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Test</title>
  </head>
  <body>
    Testing
    <button id="genExcel">Direct Download</button>
    <button id="genExcelFlask">Flask Download</button>
  </body>

  <script>
    var btn = document.getElementById("genExcel");
    var btnFlask = document.getElementById("genExcelFlask");

    btn.addEventListener("click", (e) => {
      fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then((resp) => resp.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          // the filename you want
          a.download = "todo-1.json";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          alert("your file has downloaded!"); // or you know, something with better UX...
        })
        .catch(() => alert("oh no!"));
    });

    btnFlask.addEventListener("click", (e) => {
      fetch("{{ url_for('createExcel') }}")
        .then((resp) => resp.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          // the filename you want
          a.download = "test.xlsx";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          alert("your file has downloaded!"); // or you know, something with better UX...
        })
        .catch(() => alert("oh no!"));
    });
  </script>
</html>

Flask Function

from flask import Flask, render_template, request, url_for, send_file

@app.route('/genexcel', methods=["GET", "POST"])
def createExcel():
    if request.method == 'POST':
        data = request.json
        print(data)
        # process json data

    file_path = 'static/files/test.xlsx'
    return send_file(file_path, attachment_filename='test.xlsx', as_attachment=True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM