首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用烧瓶下载excel文件并作出反应?

如何使用烧瓶下载excel文件并作出反应?
EN

Stack Overflow用户
提问于 2022-03-24 14:42:26
回答 1查看 326关注 0票数 0

我正在尝试下载xlsx文件。我发布了一个id,并使用它从数据库获取数据。然后,我可以创建一个excel文件,但我无法下载它。

我的后端代码:

代码语言:javascript
复制
from flask import Flask
from flask import request, jsonify, make_response, json, send_file, redirect, url_for,send_from_directory
from bson.json_util import dumps
from flask_cors import CORS
import dbConnections.Test as db
import os

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}}, support_credentials=True)


@app.route("/test-report", methods=["POST"])
def downloadTestReport():
    req = request.get_json();
    results = db.GetTestResult(req)
    return send_file('foo.xlsx', as_attachment=True)

if __name__ =="__main__":
    app.run(debug=True)

我的前端代码是:

代码语言:javascript
复制
    let downloadReport = (e)=>{
        if(e.field ==="downloadReport"){
            const objId=  {testId: e.row.objId};
            
            axios.post('http://127.0.0.1:5000/test-report', objId)
            .then(function (response) { 
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });       
        }
    }

我的控制台上的结果是:

我想下载excel文件,这是返回。

EN

回答 1

Stack Overflow用户

发布于 2022-09-15 18:46:25

为了在代码中显示Ethan的注释,假设后端烧瓶代码按应有的方式发送Excel文件,您的前端代码应该如下所示:

代码语言:javascript
复制
                axios('/test-report', {
                    method: 'GET', //Pretty sure you want a GET method but otherwise POST methods can still return something too.
                    responseType: 'blob', // important
                }).then((response) => { //Creates an <a> tag hyperlink that links the excel sheet Blob object to a url for downloading.
                    const url = window.URL.createObjectURL(new Blob([response.data]));
                    const link = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', `${Date.now()}.xlsx`); //set the attribute of the <a> link tag to be downloadable when clicked and name the sheet based on the date and time right now.
                    document.body.appendChild(link);
                    link.click(); //programmatically click the link so the user doesn't have to
                    document.body.removeChild(link);
                    URL.revokeObjectURL(url); //important for optimization and preventing memory leak even though link element has already been removed. In the case of long running apps that haven't been reloaded many times.    
                });

这指的是:

//https://stackoverflow.com/questions/41938718/how-to-download-files-using-axios?noredirect=1&lq=1

How to download excel in response from api react.js

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71604528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档